Elad Benda
Elad Benda

Reputation: 36654

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 ?

Upvotes: 1

Views: 269

Answers (1)

Alex K.
Alex K.

Reputation: 175766

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;

Upvotes: 1

Related Questions