gpt4 book ai didi

Javascript:对非 html 字符串转义 <>,但保留 html

转载 作者:行者123 更新时间:2023-12-03 06:13:36 25 4
gpt4 key购买 nike

我有一些包含 HTML 的文本(将在浏览器中呈现),以及带有 <> 的任意字符串。 。有没有办法转义这些任意标签,但保留 HTML?如果有帮助的话,正在解析的 HTML 受到非常严格的控制,并且只允许标签的子集( bistrongbr )

例如。鉴于此文本:

<strong>Foobar</strong> <some other whatever>

我需要

<strong>Foobar</strong> &lt;some other whatever&gt;

最佳答案

一个便宜的选择是替换 <>带有占位符,然后在“良好”上下文中恢复它们:

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, '&lt;')
.replace(/\x02/g, '&gt;')

console.log(text)

一个不太便宜但更正确的解决方案是使用(事件驱动的)html 解析器并转义不需要的东西。

关于Javascript:对非 html 字符串转义 <>,但保留 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39209950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com