使用jQuery转义HTML [英] Escape HTML using jQuery
问题描述
我想出了一个使用jQuery逃避HTML的攻击,我想知道是否有人看到它的问题。
I came up with a hack to escape HTML using jQuery and I'm wondering if anyone sees a problem with it.
$('<i></i>').text(TEXT_TO_ESCAPE).html();
< i>
标签只是一个虚拟的,因为jQuery需要一个容器来设置文本。
The <i>
tag is just a dummy as jQuery needs a container to set the text of.
有没有更简单的方法呢?请注意,我需要存储在变量中的文本,而不是显示(否则我可以调用 elem.text(TEXT_TO_ESCAPE);
)。
Is there perhaps an easier way to do this? Note that I need the text stored in a variable, not for display (otherwise I could just call elem.text(TEXT_TO_ESCAPE);
).
谢谢!
推荐答案
这是一个非常标准的方法,我的版本使用< div>
虽然:
That's a pretty standard way of doing it, my version used a <div>
though:
return $('<div/>').text(t).html();
尽管Mike Samuel指出,这在技术上并不是100%安全,但在实践中可能相当安全
This isn't technically 100% safe though as Mike Samuel notes but it is probably pretty safe in practice.
当前的Prototype.js执行此操作:
The current Prototype.js does this:
function escapeHTML() {
return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
但是它曾经使用将文本放在div中并提取HTML 窍门。
But it used to use the "put text in a div and extract the HTML" trick.
还有 _。在下划线
中转义,这样做是这样的:
There's also _.escape
in Underscore, that does it like this:
// List of HTML entities for escaping.
var htmlEscapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
};
// Regex containing the keys listed immediately above.
var htmlEscaper = /[&<>"'\/]/g;
// Escape a string for HTML interpolation.
_.escape = function(string) {
return ('' + string).replace(htmlEscaper, function(match) {
return htmlEscapes[match];
});
};
这与Prototype是一样的。大多数JavaScript最近都有Underscore可用,所以我倾向于使用 _。escape
这些天。
That's pretty much the same approach as Prototype's. Most of the JavaScript I do lately has Underscore available so I tend to use _.escape
these days.
这篇关于使用jQuery转义HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!