我想通过JavaScript函数将文本显示为HTML。如何在JavaScript中转义HTML特殊字符?有API吗?


当前回答

找到一个更好的解决方案是很有趣的:

var escapeHTML = function(unsafe) {
  return unsafe.replace(/[&<"']/g, function(m) {
    switch (m) {
      case '&':
        return '&amp;';
      case '<':
        return '&lt;';
      case '"':
        return '&quot;';
      default:
        return '&#039;';
    }
  });
};

我没有解析>,因为它没有破坏结果中的XML/HTML代码。

以下是基准测试:http://jsperf.com/regexpairs 此外,我还创建了一个通用转义函数:http://jsperf.com/regexpairs2

其他回答

我想出了这个解决方案。

假设我们想向元素添加一些HTML,其中包含来自用户或数据库的不安全数据。

var unsafe = 'some unsafe data like <script>alert("oops");</script> here';

var html = '';
html += '<div>';
html += '<p>' + unsafe + '</p>';
html += '</div>';

element.html(html);

它对于XSS攻击是不安全的。现在加上这个: $ (document.createElement (div)) . html(不安全)。text ();

就是这样

var unsafe = 'some unsafe data like <script>alert("oops");</script> here';

var html = '';
html += '<div>';
html += '<p>' + $(document.createElement('div')).html(unsafe).text(); + '</p>';
html += '</div>';

element.html(html);

对我来说,这比使用.replace()容易得多,它会删除!!所有可能的HTML标签(我希望)。

这里有一个几乎适用于所有浏览器的解决方案:

function escapeHtml(unsafe)
{
    return unsafe
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
 }

如果你只支持现代浏览器(2020+),那么你可以使用新的replaceAll函数:

const escapeHtml = (unsafe) => {
    return unsafe.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#039;');
}

显示未编码文本的最简洁和有效的方法是使用textContent属性。

比使用innerHTML更快。这还没有考虑到逃逸开销。

document.body.textContent = 'a <b> c </b>';

函数escapeHtml (html) { var text = document.createTextNode(html); var p = document.createElement('p'); p.appendChild(文本); 返回p.innerHTML; } //在输入时转义并打印结果 document.querySelector(“输入”)。addEventListener('input', e => { console.clear (); console.log(escapeHtml(e.t target.value)); }); <输入风格= '宽度:90%;填充:6 px;占位符= ' & lt; b&gt; cool&lt; / b&gt; " >

DOM元素支持通过赋值innerText将文本转换为HTML。innerText不是一个函数,但是给它赋值就好像文本被转义了一样。

document.querySelectorAll('#id')[0].innerText = 'unsafe " String >><>';