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


当前回答

ES6一行程序的解决方案来自mustache.js

const escapeHTML = str => (str+'').replace(/[&<>"'`=\/]/g, s => ({'&': '&amp;','<': '&lt;','>': '&gt;','"': '&quot;',"'": '&#39;','/': '&#x2F;','`': '&#x60;','=': '&#x3D;'})[s]);

其他回答

这是一个简洁明了的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;');
}

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

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

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

我增强了mustache.js示例,将escapeHTML()方法添加到字符串对象中。

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

String.prototype.escapeHTML = function() {
    return String(this).replace(/[&<>"'\/]/g, function (s) {
        return __entityMap[s];
    });
}

这样就很容易使用"Some <text>, more Text&Text".escapeHTML()

很容易使用下划线:

_.escape(string) 

下划线是一个实用库,它提供了很多原生js不提供的功能。还有lodash,它是与下划线相同的API,但被重写以提高性能。

function htmlDecode(t){
   if (t) return $('<div />').html(t).text();
}

效果非常好