Fastest method to escape HTML tags as HTML entities?

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

    Martijn's method as single function with handling " mark (using in javascript) :

    function escapeHTML(html) {
        var fn=function(tag) {
            var charsToReplace = {
                '&': '&',
                '<': '<',
                '>': '>',
                '"': '"'
            };
            return charsToReplace[tag] || tag;
        }
        return html.replace(/[&<>"]/g, fn);
    }
    

提交回复
热议问题