有人知道一个简单的方法来转义HTML从字符串在jQuery?我需要能够传递一个任意字符串,并有它正确转义显示在HTML页面(防止JavaScript/HTML注入攻击)。我确信可以通过扩展jQuery来实现这一点,但目前我对框架的了解还不够,无法实现这一点。
当前回答
我知道我来这个派对有多晚,但我有一个非常简单的解决方案,不需要jQuery。
escaped = new Option(unescaped).innerHTML;
编辑:不转义引号。需要转义引号的唯一情况是,内容将内联粘贴到HTML字符串中的属性。我很难想象这样做会是好的设计。
编辑3:要获得最快的解决方案,请检查上面萨拉姆的答案。这个是最短的。
其他回答
这是一个简洁明了的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, ''');
}
如果你转义HTML,只有三个我能想到,这将是真正必要的:
html.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
根据您的用例,您可能还需要执行“to "”之类的操作。如果列表足够大,我就使用数组:
var escaped = html;
var findReplace = [[/&/g, "&"], [/</g, "<"], [/>/g, ">"], [/"/g, """]]
for(var item in findReplace)
escaped = escaped.replace(findReplace[item][0], findReplace[item][1]);
encodeURIComponent()只会对url进行转义,而不会对HTML进行转义。
试着强调。它与jQuery一起工作。
_.str.escapeHTML('<div>Blah blah blah</div>')
输出:
'<div>Blah blah blah</div>'
function htmlDecode(t){
if (t) return $('<div />').html(t).text();
}
效果非常好
简单的JavaScript转义示例:
function escapeHtml(text) {
var div = document.createElement('div');
div.innerText = text;
return div.innerHTML;
}
escapeHtml("<script>alert('hi!');</script>")
// "<script>alert('hi!');</script>"