【发布时间】:2022-01-12 12:30:12
【问题描述】:
我需要替换小于或大于 (< >) 的字符,但保留任何 html 标签(简单标签会像 <b>text</b> 一样不带参数)。
所以下面的输入:
<b>> 0.5 < 0.4</b> - <>
应该是:
<b>> 0.5 < 0.4</b> - <>
我现在设法找到和编辑的是这个 expr:
<\/?[a-z][a-z0-9]*[^>\s]*>|([<>])
它将< 和> 字符分组,但它也匹配我不需要替换的标签
统一更新: 感谢@Sree Kumar,这是最终的功能:
String.prototype.replaceAt = function (index, char) {
let arr = this.split('');
arr[index] = char;
return arr.join('');
};
String.prototype.escape = function () {
let p = /(?:<[a-zA-Z]+>)|(?:<\/[a-zA-Z]+>)|(?<lt><)|(?<gt>>)/g,
result = this,
match = p.exec(result);
while (match !== null) {
if (match.groups.lt !== undefined) {
result = result.replaceAt(match.index, '<');
}
else if (match.groups.gt !== undefined) {
result = result.replaceAt(match.index, '>');
}
match = p.exec(result);
}
return result;
};
【问题讨论】:
-
哪些标签是“简单”的?请提供明确的要求。
-
@WiktorStribiżew 任何没有参数的标签都可以,我需要保持简单的 html 格式。如果我设法保留带有参数的标签会很好,但这不是必需的
-
.replace(/<\s*\/?\s*\w+\s*\/?\s*>|(<)|(>)/g, (m, g1, g2) => g2 ? '&gt;' : g1 ? '&lt;' : m)之类的东西可能会起作用。或.replace(/<\s*\/?\s*\w+[^>]*>|(<)|(>)/g, (m, g1, g2) => g2 ? '&gt;' : g1 ? '&lt;' : m)。这并不精确,但可能就足够了。为了使其更精确,您需要列出标签,以避免匹配<my_word>之类的字符串。 -
您愿意使用命名组吗?然后,您可以命名您感兴趣的组并仅获得该组。如果是
null,则丢弃。
标签: javascript regex