识别 <, >, & 并将其替换为 < ,> , & 在给定字符串中,它们单独出现,而不是 html 或 ssml 标记的一部分 [关闭]

问题描述 投票:0回答:1

需要一个 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 &lt; is a non closing bracket like this &lt;3.'

尝试了多种正则表达式逻辑,但其中一种或另一种边缘情况总是失败。任何帮助将不胜感激。

javascript regex string algorithm regexp-replace
1个回答
0
投票

您可以匹配所有标签并用占位符替换它们。之后,您可以将所有 HTML 实体替换为相应层的代码。最后就可以恢复原来的标签了。

我选择了

{@[n]}
的占位符模式,其中
n
是从
0
开始的索引(由
placeholders
数组的长度控制)。

const TAG_PATTERN = /<\/?[^>]+(>|$)/g;
  
const entityMap = {
  '&' : '&amp;',
  '<' : '&lt;',
  '>' : '&gt;',
  '"' : '&quot;',
  "'" : '&#39;'
};
  
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> &amp; <i>italic</i> text.
While this &lt; is a non closing bracket like this &lt;3.
Also, 1 &gt; 0 &amp; &quot;quoted&quot; text with single &#39;quotes&#39;.
© www.soinside.com 2019 - 2024. All rights reserved.