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

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

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

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


当前回答

js提供了一个函数:

_.escape(string)

转义插入HTML中的字符串,替换&、<、>、"和'字符。

http://underscorejs.org/#escape

它不是内置的JavaScript函数,但如果您已经在使用Underscore.js,如果要转换的字符串不是太大,那么它是比编写自己的函数更好的选择。

其他回答

function htmlEscape(str){
    return str.replace(/[&<>'"]/g,x=>'&#'+x.charCodeAt(0)+';')
}

该解决方案使用字符的数字代码,例如<被&#60;取代。

虽然它的性能略差于使用映射的解决方案,但它具有以下优点:

不依赖于库或DOM 非常容易记住(你不需要记住5个HTML转义字符) 少的代码 相当快(仍然比5个链式替换快)

你可能不需要这样的函数。由于您的代码已经在浏览器中*,您可以直接访问DOM,而不是生成和编码HTML,浏览器必须向后解码才能实际使用。

使用innerText属性可以安全地将纯文本插入到DOM中,并且比使用任何现有的转义函数快得多。甚至比将静态预编码字符串赋值给innerHTML还要快。

使用classList编辑类,使用dataset设置数据属性,使用setAttribute设置其他类。

所有这些都能帮你逃脱。更准确地说,不需要转义,也不需要在**下面执行编码,因为您正在处理HTML (DOM的文本表示)。

// use existing element var author = 'John "Superman" Doe <john@example.com>'; var el = document.getElementById('first'); el.dataset.author = author; el.textContent = 'Author: '+author; // or create a new element var a = document.createElement('a'); a.classList.add('important'); a.href = '/search?q=term+"exact"&n=50'; a.textContent = 'Search for "exact" term'; document.body.appendChild(a); // actual HTML code console.log(el.outerHTML); console.log(a.outerHTML); .important { color: red; } <div id="first"></div>

*此答案不适用于服务器端JavaScript用户(Node.js等)

** Unless you explicitly convert it to actual HTML afterwards. E.g. by accessing innerHTML - this is what happens when you run $('<div/>').text(value).html(); suggested in other answers. So if your final goal is to insert some data into the document, by doing it this way you'll be doing the work twice. Also you can see that in the resulting HTML not everything is encoded, only the minimum that is needed for it to be valid. It is done context-dependently, that's why this jQuery method doesn't encode quotes and therefore should not be used as a general purpose escaper. Quotes escaping is needed when you're constructing HTML as a string with untrusted or quote-containing data at the place of an attribute's value. If you use the DOM API, you don't have to care about escaping at all.

这就是HTML编码。没有原生javascript函数可以做到这一点,但你可以谷歌,并做一些漂亮的。

例如,http://sanzon.wordpress.com/2008/05/01/neat-little-html-encoding-trick-in-javascript/

编辑: 以下是我的测试结果:

var div = document.createElement('div');
  var text = document.createTextNode('<htmltag/>');
  div.appendChild(text);
  console.log(div.innerHTML);

输出:&lt; htmltag / &gt;

这里有一个转义HTML的函数:

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

为了解码:

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

反一:

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