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


当前回答

我想我找到了正确的方法……

// Create a DOM Text node:
var text_node = document.createTextNode(unescaped_text);

// Get the HTML element where you want to insert the text into:
var elem = document.getElementById('msg_span');

// Optional: clear its old contents
//elem.innerHTML = '';

// Append the text node into it:
elem.appendChild(text_node);

其他回答

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

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

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

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

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;');
}

你可以使用jQuery的.text()函数。

例如:

http://jsfiddle.net/9H6Ch/

来自jQuery文档关于.text()函数:

我们需要意识到这种方法 转义提供的字符串 必须这样才能渲染 正确的HTML格式。为了做到这一点,它调用 DOM方法。createtextnode () 不会将字符串解释为HTML。

以前版本的jQuery文档是这样写的(强调添加):

我们需要知道这个方法在必要时转义提供的字符串,以便在HTML中正确呈现。为此,它调用DOM方法. createtextnode(),该方法将特殊字符替换为对应的HTML实体(例如&amplt表示<)。

我想我找到了正确的方法……

// Create a DOM Text node:
var text_node = document.createTextNode(unescaped_text);

// Get the HTML element where you want to insert the text into:
var elem = document.getElementById('msg_span');

// Optional: clear its old contents
//elem.innerHTML = '';

// Append the text node into it:
elem.appendChild(text_node);

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

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