JavaScript 中的 HtmlSpecialChars 等价物是什么? [英] What is the HtmlSpecialChars equivalent in JavaScript?
问题描述
显然,这比我想象的更难找到.它甚至是那么简单...
Apparently, this is harder to find than I thought it would be. And it even is so simple...
是否有与 PHP 的 htmlspecialchars 等价的函数内置于 JavaScript 中?我知道自己实现它相当容易,但使用内置函数(如果可用)更好.
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.
对于那些不熟悉 PHP 的人,htmlspecialchars 将诸如 <htmltag/>
之类的东西翻译成 <htmltag/>
For those unfamiliar with PHP, htmlspecialchars translates stuff like <htmltag/>
into <htmltag/>
我知道 escape()
和 encodeURI()
不能这样工作.
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
这是正常工作的代码:
function escapeHtml(text) {
return text
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
更新
以下代码将产生与上述相同的结果,但性能更好,尤其是在大文本块上(感谢 jbo5112).
function escapeHtml(text) {
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
这篇关于JavaScript 中的 HtmlSpecialChars 等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!