显然,这比我想象的要难找。它甚至是如此简单……

JavaScript中是否内置了与PHP的htmlspecialchars相同的函数?我知道自己实现它相当容易,但如果可用的话,使用内置函数会更好。

对于那些不熟悉PHP的人,htmlspecialchars将<htmltag/>转换为&lt;htmltag/&gt;

我知道escape()和encodeURI()不是这样工作的。


当前回答

我希望这能赢得比赛,因为它的性能和最重要的不是使用.replace('&','&').replace('<','<')的链式逻辑…

var mapObj = {
   '&':  "&amp;",
   '<':  "&lt;",
   '>':  "&gt;",
   '"':  "&quot;",
   '\'': "&#039;"
};
var re = new RegExp(Object.keys(mapObj).join("|"), "gi");

function escapeHtml(str)
{
    return str.replace(re, function(matched)
    {
        return mapObj[matched.toLowerCase()];
    });
}

console.log('<script type="text/javascript">alert('Hello World');</script>');
console.log(escapeHtml('<script type="text/javascript">alert('Hello World');</script>'));

其他回答

对于Node.js用户(或在浏览器中使用Jade运行时的用户),可以使用Jade的转义函数。

require('jade').runtime.escape(...);

如果别人在维护它,你自己写它就没有任何意义了。:)

Use:

String.prototype.escapeHTML = function() {
        return this.replace(/&/g, "&amp;")
                   .replace(/</g, "&lt;")
                   .replace(/>/g, "&gt;")
                   .replace(/"/g, "&quot;")
                   .replace(/'/g, "&#039;");
    }

示例:

var toto = "test<br>";
alert(toto.escapeHTML());

您的解决方案代码有一个问题——它只转义每个特殊字符的第一次出现。例如:

escapeHtml('Kip\'s <b>evil</b> "test" code\'s here');
Actual:   Kip&#039;s &lt;b&gt;evil</b> &quot;test" code's here
Expected: Kip&#039;s &lt;b&gt;evil&lt;/b&gt; &quot;test&quot; code&#039;s here

下面是正常工作的代码:

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

更新

下面的代码将产生与上面相同的结果,但它的性能更好,特别是在大块文本上(感谢jbo5112)。

function escapeHtml(text) {
  var map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };
  
  return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}

使用jQuery可以像这样:

var escapedValue = $('<div/>').text(value).html();

用jQuery转义HTML字符串

正如注释中提到的,双引号和单引号在此实现中保持原样。这意味着如果您需要将元素属性作为原始html字符串,则不应使用此解决方案。

这与这个问题没有直接关系,但在JS中可以通过:

> String.fromCharCode(8212);
> "—"

这也适用于TypeScript。