有人知道一个简单的方法来转义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

其他回答

一个速度优化版本:

function escapeHtml(s) { let out = ""; let p2 = 0; for (let p = 0; p < s.length; p++) { let r; switch (s.charCodeAt(p)) { case 34: r = "&quot;"; break; // " case 38: r = "&amp;" ; break; // & case 39: r = "&#39;" ; break; // ' case 60: r = '&lt;' ; break; // < case 62: r = '&gt;' ; break; // > default: continue; } if (p2 < p) { out += s.substring(p2, p); } out += r; p2 = p + 1; } if (p2 == 0) { return s; } if (p2 < s.length) { out += s.substring(p2); } return out; } const s = "Hello <World>!"; document.write(escapeHtml(s)); console.log(escapeHtml(s));

如果你不防止再次逃逸,所有的解决方案都是无用的,例如,大多数解决方案将继续逃逸&到&

escapeHtml = function (s) {
    return s ? s.replace(
        /[&<>'"]/g,
        function (c, offset, str) {
            if (c === "&") {
                var substr = str.substring(offset, offset + 6);
                if (/&(amp|lt|gt|apos|quot);/.test(substr)) {
                    // already escaped, do not re-escape
                    return c;
                }
            }
            return "&" + {
                "&": "amp",
                "<": "lt",
                ">": "gt",
                "'": "apos",
                '"': "quot"
            }[c] + ";";
        }
    ) : "";
};

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

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

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

输出:

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

简单的JavaScript转义示例:

function escapeHtml(text) {
    var div = document.createElement('div');
    div.innerText = text;
    return div.innerHTML;
}

escapeHtml("<script>alert('hi!');</script>")
// "&lt;script&gt;alert('hi!');&lt;/script&gt;"