Fastest method to escape HTML tags as HTML entities?

前端 未结 12 1638
-上瘾入骨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:51

    You could try passing a callback function to perform the replacement:

    var tagsToReplace = {
        '&': '&',
        '<': '<',
        '>': '>'
    };
    
    function replaceTag(tag) {
        return tagsToReplace[tag] || tag;
    }
    
    function safe_tags_replace(str) {
        return str.replace(/[&<>]/g, replaceTag);
    }
    

    Here is a performance test: http://jsperf.com/encode-html-entities to compare with calling the replace function repeatedly, and using the DOM method proposed by Dmitrij.

    Your way seems to be faster...

    Why do you need it, though?

提交回复
热议问题