从 html 正文中删除所有 HTML 标签,除了 <a>、<br>、<b> 和 <img>

Remove all HTML tags from a html body except <a>, <br>, <b> and <img>

在阅读一些电子邮件 HTML 正文时,我经常有很多 HTML 标签,我不再想要了。

如何从字符串中删除,在 Javascript 中,所有 HTML 标签如:

<anything ...>

</anything>

除了少数情况 <x ...></x><x ... /> x 是:

我想到了类似的东西:

s.replace(/<[^a].*>/g, '');

但我不知道该怎么做。

示例:

<div id="hello">Hello</div><a href="test">Youhou</a>` 

应该变成

Hello<a href="test">Youhou</a>

注意:我正在寻找几行代码的解决方案,它可以在 90% 的时间工作(电子邮件正文来自我自己的电子邮件,所以我没有包含任何恶意内容),而不是需要第三方 tool/library.

的完整解决方案

您可以将函数作为第二个参数传递给 .replace,这将决定如何处理输出。

str.replace(/<[^a].*>/g, function (s) { /* do something with s */ });

请参阅有关替换的 MDN 文档:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

尝试替换

<\/?(?!(a|br|b|img)\b)\w+[^>]*>

没有

<\/? 匹配开头 <,后面可以选择跟一个 /

(?!(a|br|b|img)\b) 否定前瞻确保我们不匹配 abrbimg 标签。

\w+[^>]*> 匹配标签的其余部分。

Here at regex101.

这不是很漂亮,但应该能满足你的要求

html.replace(/<\/?([^\s>])[^>]*>/gi,function(tag,tagName){
    return ['a','b','br','img'].indexOf(tagName.toLowerCase()) >= 0? tag: '';
})

\/? 可选斜杠 ([^\s>]) 匹配标记名 [^>]* 属性空格等