【问题标题】:Change the JavaScript function to delete HTML tags, except <br> [duplicate]更改 JavaScript 函数以删除 HTML 标记,除了 <br> [重复]
【发布时间】:2020-07-18 07:52:21
【问题描述】:

我有以下函数可以消除html代码的所有标记:

function saringtags(r, l) {
    for (var e = r.split("<"), n = 0; n < e.length; n++) - 1 != e[n].indexOf(">") && (e[n] = e[n].substring(e[n].indexOf(">") + 1, e[n].length));
    return e = e.join(""), e = e.substring(0, l - 1)
}

问题是这样的:

<div class="lyric">
<blockquote>
It's nine o'clock on a Saturday<br>
The regular crowd shuffles in<br>
There's an old man sitting next to me<br>
Makin' love to his tonic and gin<br>
</blockquote>
</div>

变成这样:

It's nine o'clock on a SaturdayThe regular crowd shuffles inThere's an old man sitting next to meMakin' love to his tonic and gin

如何为函数中的&lt;br&gt; 标记创建异常? 这个结果就是我需要的:

It's nine o'clock on a Saturday<br>The regular crowd shuffles in<br>There's an old man sitting next to me<br>Makin' love to his tonic and gin

【问题讨论】:

  • 首先将所有&lt;br&gt;替换为\n

标签: javascript html


【解决方案1】:

使用正则表达式:

/<.>/g

html.replace(/<.*[^br]>/g,'')

https://regexr.com/58l77

【讨论】:

  • 此解决方案运行良好。谢谢
【解决方案2】:

希望对你有所帮助

var text = `<div class="lyric"><blockquote>It's nine o'clock on a Saturday<br>The regular crowd shuffles in<br>There's an old man sitting next to me<br>Makin' love to his tonic and gin<br></blockquote></div>"`;

var str = text.replace(/<br>/gi, ' vvvvv ').replace(/<\/?[^>]+(>|$)/g, "").replace(/ vvvvv /gi, '<br>');

console.log(str);

【讨论】:

    【解决方案3】:

    你重新实现了innerText

    console.log(document.getElementsByClassName('lyric')[0].innerText)
    <div class="lyric">
    <blockquote>
    It's nine 
    o'clock on a 
    Saturday<br>
    The regular crowd shuffles in<br>
    There's an old man <br>sitting next to me<br>
    Makin' love to his tonic and gin<br>
    </blockquote>
    </div>

    (如果你真的需要&lt;br&gt; 标签,你可以在之后用&lt;br&gt; 替换换行符。这比尝试通过正则表达式或其他字符串操作方法来操作HTML 更不容易出错。)

    【讨论】:

    • 是的 - 但你并不总是需要 \n 所在的
      ,以及没有新行的
      呢?它会丢失。
    • @MrAleister innerText 为您处理这两个问题;它从输入 HTML 中删除现有的换行符,然后将 &lt;br&gt;&lt;p&gt; 转换为换行符。我已经更新了示例来演示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多