1

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 ?

Alex K.
  • 171,639
  • 30
  • 264
  • 288
Elad Benda
  • 35,076
  • 87
  • 265
  • 471

1 Answers1

1

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;
Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • wouldn't native method escape() be enought? Is there any native method that could achieve the same? – Elad Benda Jun 29 '11 at 17:19
  • 1
    Well escape is for url encoding; it would convert < to something like %3Cb which - if you were to write it to the page (which is what i assume your doing) - you would see as "%3Cb". The example above would convert to < which would be rendered correctly as the < character. – Alex K. Jun 29 '11 at 18:49
  • Here are some alternatives using .replace/jq; http://stackoverflow.com/questions/1787322/htmlspecialchars-equivalent-in-javascript – Alex K. Jun 29 '11 at 18:51