Fastest method to escape HTML tags as HTML entities?

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

    All-in-one script:

    // HTML entities Encode/Decode
    
    function htmlspecialchars(str) {
        var map = {
            "&": "&",
            "<": "<",
            ">": ">",
            "\"": """,
            "'": "'" // ' -> ' for XML only
        };
        return str.replace(/[&<>"']/g, function(m) { return map[m]; });
    }
    function htmlspecialchars_decode(str) {
        var map = {
            "&": "&",
            "<": "<",
            ">": ">",
            """: "\"",
            "'": "'"
        };
        return str.replace(/(&|<|>|"|')/g, function(m) { return map[m]; });
    }
    function htmlentities(str) {
        var textarea = document.createElement("textarea");
        textarea.innerHTML = str;
        return textarea.innerHTML;
    }
    function htmlentities_decode(str) {
        var textarea = document.createElement("textarea");
        textarea.innerHTML = str;
        return textarea.value;
    }
    

    http://pastebin.com/JGCVs0Ts

提交回复
热议问题