您的解决方案代码存在问题 - 它只会对每个特殊字符的第一次出现进行转义。例如:
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]; });
}