将HTML标签转义为HTML实体的最快方法? [英] Fastest method to escape HTML tags as HTML entities?
问题描述
我正在撰写一个Chrome扩展程序,它涉及到执行以下作业的很多:清理可能包含HTML标记的字符串,方法是转换 <
,>
和&
至&
,& gt;
和& amp;
(换句话说,就像PHP的 htmlspecialchars(str,ENT_NOQUOTES)
) - 我不认为有任何真实的需要转换双引号字符。)
这是迄今为止我发现的最快的函数:
function safe_tags(str){
return str.replace(/& / g,'& amp;')。replace(/< / g,'& lt ;')。replace(/> / g,'& gt;');
}
但是,如果我必须运行几千个字符串,它一气呵成。
任何人都可以改进吗?它主要用于10到150个字符之间的字符串,如果这有所帮助的话。
(我有一个想法是不打扰编码大于号 - 是否会有真正的危险?)
<您可以尝试传递一个回调函数来执行替换:
<$ c $ c> var tagsToReplace = {
'&':'& amp;',
'<':'& lt;',
'>':'& '
};
函数replaceTag(tag){
返回tagsToReplace [tag] ||标签;
}
函数safe_tags_replace(str){
return str.replace(/ [&<>] / g,replaceTag);
}
以下是一个性能测试: http://jsperf.com/encode-html-entities 与调用替换
函数,并使用Dmitrij提出的DOM方法。
I'm writing a Chrome extension that involves doing a lot of the following job: sanitizing strings that might contain HTML tags, by converting <
, >
and &
to <
, >
and &
, respectively.
(In other words, the same as PHP's htmlspecialchars(str, ENT_NOQUOTES)
– I don't think there's any real need to convert double-quote characters.)
This is the fastest function I have found so far:
function safe_tags(str) {
return str.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>') ;
}
But there's still a big lag when I have to run a few thousand strings through it in one go.
Can anyone improve on this? It's mostly for strings between 10 and 150 characters, if that makes a difference.
(One idea I had was not to bother encoding the greater-than sign – would there be any real danger with that?)
You could try passing a callback function to perform the replacement:
var tagsToReplace = {
'&': '&',
'<': '<',
'>': '>'
};
function replaceTag(tag) {
return tagsToReplace[tag] || tag;
}
function safe_tags_replace(str) {
return str.replace(/[&<>]/g, replaceTag);
}
Here is a performance test: http://jsperf.com/encode-html-entities to compare with calling the replace
function repeatedly, and using the DOM method proposed by Dmitrij.
Your way seems to be faster...
Why do you need it, though?
这篇关于将HTML标签转义为HTML实体的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!