HtmlSpecialChars等效于Javascript? [英] HtmlSpecialChars equivalent in Javascript?
问题描述
有没有相当于PHP内置的Javascript的htmlspecialchars的功能?我知道这是很容易实现的,但是使用内置函数(如果有的话)只是更好。
对于那些不熟悉PHP的人来说,htmlspecialchars会翻译像< htmltag />
到& lt; htmltag /& gt;
我知道, escape()
和 encodeURI()
不能这样工作。
解决方案代码有问题 - 它只会逃避每个特殊字符的首次出现。例如:
escapeHtml('Kip\'s< b> evil< / b>testcode \\在这里)
实际:Kip&#039; s& lt; b& gt; evil< / b> &test代码在这里
预期:Kip&#039; s& lt; b& gt; evil& lt; / b& quot; test& quot; code&#039;在这里
这里是正常工作的代码:
function escapeHtml(text){
return text
.replace(/& / g,& amp;)
.replace (/< / g,&)
.replace(/> / g,& gt)
.replace(// g,& ;)
.replace(/'/ g,&#039;);
}
更新
以下代码将产生与上述相同的结果,但其性能更好,特别是在大块文本上(感谢 jbo5112 )。
function escapeHtml(text){
var map =
'&':'& amp;',
'<':'& lt;',
'>':'& $ b'':'& quot;',
':'&#039;'
};
return text.replace(/ ;”'] / g,function(m){return map [m];});
}
Apparently, this is harder to find than I thought it would be. And it even is so simple...
Is there a function equivalent to PHP's htmlspecialchars built into Javascript? I know it's fairly easy to implement that yourself, but using a built-in function, if available, is just nicer.
For those unfamiliar with PHP, htmlspecialchars translates stuff like <htmltag/>
into <htmltag/>
I know that escape()
and encodeURI()
do not work this way.
There is a problem with your solution code--it will only escape the first occurrence of each special character. For example:
escapeHtml('Kip\'s <b>evil</b> "test" code\'s here');
Actual: Kip's <b>evil</b> "test" code's here
Expected: Kip's <b>evil</b> "test" code's here
Here is code that works properly:
function escapeHtml(text) {
return text
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
Update
The following code will produce identical results to the above, but it performs better, particularly on large blocks of text (thanks jbo5112).
function escapeHtml(text) {
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
这篇关于HtmlSpecialChars等效于Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!