有人知道一个简单的方法来转义HTML从字符串在jQuery?我需要能够传递一个任意字符串,并有它正确转义显示在HTML页面(防止JavaScript/HTML注入攻击)。我确信可以通过扩展jQuery来实现这一点,但目前我对框架的了解还不够,无法实现这一点。
当前回答
function htmlDecode(t){
if (t) return $('<div />').html(t).text();
}
效果非常好
其他回答
如果你走的是正则表达式路线,上面tghw的例子中就有一个错误。
<!-- WON'T WORK - item[0] is an index, not an item -->
var escaped = html;
var findReplace = [[/&/g, "&"], [/</g, "<"], [/>/g,">"], [/"/g,
"""]]
for(var item in findReplace) {
escaped = escaped.replace(item[0], item[1]);
}
<!-- WORKS - findReplace[item[]] correctly references contents -->
var escaped = html;
var findReplace = [[/&/g, "&"], [/</g, "<"], [/>/g, ">"], [/"/g, """]]
for(var item in findReplace) {
escaped = escaped.replace(findReplace[item[0]], findReplace[item[1]]);
}
function htmlDecode(t){
if (t) return $('<div />').html(t).text();
}
效果非常好
这是一个简洁明了的JavaScript函数。它会将诸如"a few < many"这样的文本转义为"a few <许多”。
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, '&')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
$('<div/>').text('This is fun & stuff').html(); // "This is fun & stuff"
来源:http://debuggable.com/posts/encode-html-entities-with-jquery: 480 f4dd6 - 13 - cc - 4 - ce9 - 8071 - 4710 - cbdd56cb
如果你不防止再次逃逸,所有的解决方案都是无用的,例如,大多数解决方案将继续逃逸&到&
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] + ";";
}
) : "";
};