有人知道一个简单的方法来转义HTML从字符串在jQuery?我需要能够传递一个任意字符串,并有它正确转义显示在HTML页面(防止JavaScript/HTML注入攻击)。我确信可以通过扩展jQuery来实现这一点,但目前我对框架的了解还不够,无法实现这一点。


当前回答

$('<div/>').text('This is fun & stuff').html(); // "This is fun &amp; stuff"

来源:http://debuggable.com/posts/encode-html-entities-with-jquery: 480 f4dd6 - 13 - cc - 4 - ce9 - 8071 - 4710 - cbdd56cb

其他回答

escape()和unescape()用于为url编码/解码字符串,而不是HTML。

实际上,我使用下面的代码片段来完成不需要任何框架的技巧:

var escapedHtml = html.replace(/&/g, '&amp;')
                      .replace(/>/g, '&gt;')
                      .replace(/</g, '&lt;')
                      .replace(/"/g, '&quot;')
                      .replace(/'/g, '&apos;');

这是一个简洁明了的JavaScript函数。它会将诸如"a few < many"这样的文本转义为"a few &lt;许多”。

function escapeHtmlEntities (str) {
  if (typeof jQuery !== 'undefined') {
    // Create an empty div to use as a container,
    // then put the raw text in and get the HTML
    // equivalent out.
    return jQuery('<div/>').text(str).html();
  }

  // No jQuery, so use string replace.
  return str
    .replace(/&/g, '&amp;')
    .replace(/>/g, '&gt;')
    .replace(/</g, '&lt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
}

在mustache.js中也有解决方案

var entityMap = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#39;',
  '/': '&#x2F;',
  '`': '&#x60;',
  '=': '&#x3D;'
};

function escapeHtml (string) {
  return String(string).replace(/[&<>"'`=\/]/g, function (s) {
    return entityMap[s];
  });
}

试着强调。它与jQuery一起工作。

_.str.escapeHTML('<div>Blah blah blah</div>')

输出:

'&lt;div&gt;Blah blah blah&lt;/div&gt;'

你可以很容易地用香草js做到这一点。

只需在文档中添加一个文本节点。 它将被浏览器转义。

var escaped = document.createTextNode("<HTML TO/ESCAPE/>")
document.getElementById("[PARENT_NODE]").appendChild(escaped)