Search code examples
javascripthtml-encode

Encoder.htmlEncoder in JS


On a website, I retrieve a string the user entered.

DataItem.getProperty('-----some name ----')

The problem is that some users put a <script></script> in there.

How can I escape/html-encode this string nicely ?


Solution

  • How about;

    function HTMLEncode(buff) {
        var e = document.createElement("div");
        e.appendChild(document.createTextNode(buff));
        return e.innerHTML;
    }
    
    
     In:  AAA <script>BBB</script> CCC &lt;DDD&gt;
     Out: AAA &lt;script&gt;BBB&lt;/script&gt; CCC &lt;DDD&gt;