Fastest method to escape HTML tags as HTML entities?

前端 未结 12 1552
-上瘾入骨i
-上瘾入骨i 2020-11-22 09:24

I\'m writing a Chrome extension that involves doing a lot of the following job: sanitizing strings that might contain HTML tags, by converting

12条回答
  •  独厮守ぢ
    2020-11-22 09:57

    The fastest method is:

    function escapeHTML(html) {
        return document.createElement('div').appendChild(document.createTextNode(html)).parentNode.innerHTML;
    }
    

    This method is about twice faster than the methods based on 'replace', see http://jsperf.com/htmlencoderegex/35 .

    Source: https://stackoverflow.com/a/17546215/698168

提交回复
热议问题