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

其他回答

如果你转义HTML,只有三个我能想到,这将是真正必要的:

html.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");

根据您的用例,您可能还需要执行“to "”之类的操作。如果列表足够大,我就使用数组:

var escaped = html;
var findReplace = [[/&/g, "&amp;"], [/</g, "&lt;"], [/>/g, "&gt;"], [/"/g, "&quot;"]]
for(var item in findReplace)
    escaped = escaped.replace(findReplace[item][0], findReplace[item][1]);

encodeURIComponent()只会对url进行转义,而不会对HTML进行转义。

2简单的方法,不需要JQUERY…

你可以像这样编码字符串中的所有字符:

function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}

或者只针对主要字符担心&,换行符,<,>,"和'像:

function encode(r){ return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"}) } var myString='Encode HTML entities!\n"Safe" escape <script></'+'script> & other tags!'; test.value=encode(myString); testing.innerHTML=encode(myString); /************* * \x26 is &ampersand (it has to be first), * \x0A is newline, *************/ <p><b>What JavaScript Generated:</b></p> <textarea id=test rows="3" cols="55"></textarea> <p><b>What It Renders Too In HTML:</b></p> <div id="testing">www.WHAK.com</div>

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

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

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

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

转义html特殊(UTF-8)

function htmlEscape(str) {
  return str
      .replace(/&/g, '&amp;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/\//g, '&#x2F;')
      .replace(/=/g,  '&#x3D;')
      .replace(/`/g, '&#x60;');
}

对于unescape html特殊(UTF-8)

function htmlUnescape(str) {
  return str
      .replace(/&amp;/g, '&')
      .replace(/&quot;/g, '"')
      .replace(/&#39;/g, "'")
      .replace(/&lt;/g, '<')
      .replace(/&gt;/g, '>')
      .replace(/&#x2F/g, '/')
      .replace(/&#x3D;/g, '=')
      .replace(/&#x60;/g, '`');
}