我有一些包含 HTML 的文本(将在浏览器中呈现),以及带有 <>
的任意字符串。 。有没有办法转义这些任意标签,但保留 HTML?如果有帮助的话,正在解析的 HTML 受到非常严格的控制,并且只允许标签的子集( b
、 i
、 strong
、 br
)
例如。鉴于此文本:
<strong>Foobar</strong> <some other whatever>
我需要
<strong>Foobar</strong> <some other whatever>
最佳答案
一个便宜的选择是替换 <>
带有占位符,然后在“良好”上下文中恢复它们:
allowedTags = ['strong', 'em', 'p'];
text = '<strong>Foobar</strong> <some other whatever> <b>??</b> <em>hey</em>'
text = text
.replace(/</g, '\x01')
.replace(/>/g, '\x02')
.replace(new RegExp('\x01(/?)(' + allowedTags.join('|') + ')\x02', 'g'), "<$1$2>")
.replace(/\x01/g, '<')
.replace(/\x02/g, '>')
console.log(text)
一个不太便宜但更正确的解决方案是使用(事件驱动的)html 解析器并转义不需要的东西。
关于Javascript:对非 html 字符串转义 <>,但保留 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39209950/