需要一个 Javascript 代码片段,可以识别 <, > 、 & 并在给定字符串中将其替换为 < ,> 、 & ,它们单独出现,而不是 html 或 ssml 标记的一部分。
例如-
'This is a <b>bold</b> & <i>italic</i> text. While this < is a non closing bracket like this <3.'
应转换为
'This is a <b>bold</b> & <i>italic</i> text. While this < is a non closing bracket like this <3.'
尝试了多种正则表达式逻辑,但其中一种或另一种边缘情况总是失败。任何帮助将不胜感激。
您可以匹配所有标签并用占位符替换它们。之后,您可以将所有 HTML 实体替换为相应层的代码。最后就可以恢复原来的标签了。
我选择了
{@[n]}
的占位符模式,其中 n
是从 0
开始的索引(由 placeholders
数组的长度控制)。
const TAG_PATTERN = /<\/?[^>]+(>|$)/g;
const entityMap = {
'&' : '&',
'<' : '<',
'>' : '>',
'"' : '"',
"'" : '''
};
const escapeHTMLEntitiesPreserveTags = (str) => {
const placeholders = [];
return str
// Temporarily replace all tags with placeholders
.replace(TAG_PATTERN, (match) => {
placeholders.push(match);
return `{@[${placeholders.length - 1}]}`;
})
// Escape all HTML entities in the modified string
.replace(/[&<>"']/g, (char) => entityMap[char] ?? char)
// Restore original tags
.replace(/\{@\[(\d+)\]\}/g, (_, index) => placeholders[+index]);
};
const inputText = 'This is a <b>bold</b> & <i>italic</i> text.\n' +
'While this < is a non closing bracket like this <3.\n' +
'Also, 1 > 0 & "quoted" text with single \'quotes\'.';
console.log(escapeHTMLEntitiesPreserveTags(inputText));
This is a <b>bold</b> & <i>italic</i> text.
While this < is a non closing bracket like this <3.
Also, 1 > 0 & "quoted" text with single 'quotes'.