我花了一些时间寻找转义HTML字符串的最佳方法,并在以下讨论中发现了一些有用的信息:讨论1和讨论2。这引导我使用了replaceAll函数。但之后我进行了性能测试,尝试找到相似速度的解决方案却没有成功。
这里是我最终的测试案例集。我在网络上找到它并扩展了我的尝试(底部的4个案例),但仍无法达到replaceAll()
的速度。
是什么秘密使得replaceAll()
的解决方案如此迅速?
问候!
代码片段:
String.prototype.replaceAll = function(str1, str2, ignore)
{
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
};
感谢qwerty
到目前为止,最快的情况:
html.replaceAll('&', '&').replaceAll('"', '"').replaceAll("'", ''').replaceAll('<', '<').replaceAll('>', '>');