有人知道一个简单的方法来转义HTML从字符串在jQuery?我需要能够传递一个任意字符串,并有它正确转义显示在HTML页面(防止JavaScript/HTML注入攻击)。我确信可以通过扩展jQuery来实现这一点,但目前我对框架的了解还不够,无法实现这一点。
当前回答
escape()和unescape()用于为url编码/解码字符串,而不是HTML。
实际上,我使用下面的代码片段来完成不需要任何框架的技巧:
var escapedHtml = html.replace(/&/g, '&')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/"/g, '"')
.replace(/'/g, ''');
其他回答
因为你使用的是jQuery,你可以设置元素的text属性:
// before:
// <div class="someClass">text</div>
var someHtmlString = "<script>alert('hi!');</script>";
// set a DIV's text:
$("div.someClass").text(someHtmlString);
// after:
// <div class="someClass"><script>alert('hi!');</script></div>
// get the text in a string:
var escaped = $("<div>").text(someHtmlString).html();
// value:
// <script>alert('hi!');</script>
转义html特殊(UTF-8)
function htmlEscape(str) {
return str
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\//g, '/')
.replace(/=/g, '=')
.replace(/`/g, '`');
}
对于unescape html特殊(UTF-8)
function htmlUnescape(str) {
return str
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(///g, '/')
.replace(/=/g, '=')
.replace(/`/g, '`');
}
function htmlDecode(t){
if (t) return $('<div />').html(t).text();
}
效果非常好
我知道我来这个派对有多晚,但我有一个非常简单的解决方案,不需要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, ''');
}