【问题标题】:Convert HTML text into plain text [duplicate]将 HTML 文本转换为纯文本 [重复]
【发布时间】:2018-02-08 14:10:20
【问题描述】:

是否有执行此操作的方法或函数,或者我必须检查字符串的每个字符。例如,给出我在说什么的想法。我有一个 HTML 文本,例如:

<p><strong>Welcome&nbsp;</strong>to this&nbsp;<em>message,&nbsp;</em><span style="text-decoration: underline;">you may come in peace.</span></p>

我需要将其转换为纯文本,结果为:

Welcome to this message, you may come in peace.

文本将来自一个 textarea,它是 div 和 id = editor-email 的子代。

我也想获取当前文本,但它不起作用。

var textEmail = $('#editor-email').find('textarea').text();

【问题讨论】:

  • ``` html = "

    欢迎 收到此消息 消息, 你可以平安来。

    " html = html.replace(/

标签: javascript jquery


【解决方案1】:

你可以像用纯 JS 那样做

let a = `<p><strong>Welcome&nbsp;</strong>to this&nbsp;<em>message,&nbsp;</em><span style="text-decoration: underline;">you may come in peace.</span></p>
`;

let d = document.createElement('div');
d.innerHTML = a;
console.log(d.innerText);

【讨论】:

    【解决方案2】:

    如果您正在寻找无 JQuery 的解决方案,您可以选择元素并使用.innerText:

    document.querySelector('#myElement').innerText
    

    【讨论】:

    【解决方案3】:

    我认为你需要:

    $("p").text()
    

    编辑:

    如果你想要 textarea 中的值,那么你需要:

    $("#editor-email > textarea").val();
    

    【讨论】:

    • 如果你有多个

      元素,这将不起作用

    • 如果是文本区域怎么办,我会更新我的问题以使其更清楚。
    • @JanArielSanJose 如果它是一个 textarea 然后做 $("textarea").val()
    • @KeesdeWit 看看更新的问题,它是一个 div 的孩子。我无法让它看起来有效。
    • @JanArielSanJose 检查我的更新
    猜你喜欢
    • 2014-09-24
    • 2012-04-12
    • 2014-09-08
    • 2015-01-03
    • 2017-03-20
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    相关资源
    最近更新 更多