有人知道一个简单的方法来转义HTML从字符串在jQuery?我需要能够传递一个任意字符串,并有它正确转义显示在HTML页面(防止JavaScript/HTML注入攻击)。我确信可以通过扩展jQuery来实现这一点,但目前我对框架的了解还不够,无法实现这一点。
当前回答
escape()和unescape()用于为url编码/解码字符串,而不是HTML。
实际上,我使用下面的代码片段来完成不需要任何框架的技巧:
var escapedHtml = html.replace(/&/g, '&')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/"/g, '"')
.replace(/'/g, ''');
其他回答
试着强调。它与jQuery一起工作。
_.str.escapeHTML('<div>Blah blah blah</div>')
输出:
'<div>Blah blah blah</div>'
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]]);
}
如果你转义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进行转义。
我写了一个小函数来做这个。它只转义“,&,<和>(但通常这就是你所需要的)。它比前面提出的解决方案稍微优雅一些,因为它只使用一个.replace()来完成所有的转换。(编辑2:降低代码复杂度,使函数更小更整洁,如果你对原始代码感到好奇,请参阅答案末尾。)
function escapeHtml(text) {
'use strict';
return text.replace(/[\"&<>]/g, function (a) {
return { '"': '"', '&': '&', '<': '<', '>': '>' }[a];
});
}
这是纯Javascript,没有使用jQuery。
逃避/和“too”
编辑以回应mklement的评论。
上面的函数可以很容易地扩展到包括任何字符。要指定更多要转义的字符,只需将它们插入正则表达式中的字符类(即在/[…]/g中)和chr对象中的一个条目中。(编辑2:用同样的方式缩短了这个函数。)
function escapeHtml(text) {
'use strict';
return text.replace(/[\"&'\/<>]/g, function (a) {
return {
'"': '"', '&': '&', "'": ''',
'/': '/', '<': '<', '>': '>'
}[a];
});
}
Note the above use of ' for apostrophe (the symbolic entity ' might have been used instead – it is defined in XML, but was originally not included in the HTML spec and might therefore not be supported by all browsers. See: Wikipedia article on HTML character encodings). I also recall reading somewhere that using decimal entities is more widely supported than using hexadecimal, but I can't seem to find the source for that now though. (And there cannot be many browsers out there which does not support the hexadecimal entities.)
注意:将/和'添加到转义字符列表中并不是很有用,因为它们在HTML中没有任何特殊含义,也不需要转义。
原始escapeHtml函数
编辑2:原始函数使用一个变量(chr)来存储.replace()回调所需的对象。这个变量还需要一个额外的匿名函数来限定它的范围,这使得函数(不必要地)变得更大更复杂。
var escapeHtml = (function () {
'use strict';
var chr = { '"': '"', '&': '&', '<': '<', '>': '>' };
return function (text) {
return text.replace(/[\"&<>]/g, function (a) { return chr[a]; });
};
}());
我还没有测试这两个版本中哪个更快。如果你喜欢,请在这里添加相关信息和链接。
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 如何在JSON中使用杰克逊更改字段名
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- 如何删除表中特定列的第一个字符?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?