How can I make HTML code non-execute?

What I want to do is allow the user to input a string then display that string in the web page inside a div element, but I don’t want the user to be able to add a bold tag or anything that would actually make the HTML text bold. How could I make it so the text entered by the user does not get converted into HTML code, if the text has an HTML tag in it?


here’s a neat little function to sanitize untrusted text:

function sanitize(ht){ // tested in ff, ch, ie9+
  return new Option(ht).innerHTML;

example input/output:

sanitize(" Hello <img src=data:image/png, onmouseover=alert(666) onerror=alert(666)> World");

// == " Hello &lt;img src=data:image/png, onmouseover=alert(666) onerror=alert(666)&gt; World"

It will achieve the same results as setting elm.textContent=str;, but as a function, you can use it easier inline, like to run markdown after you sanitize() so that you can pretty-format input (eg. linking URLs) without running arbitrary HTML from the user.

Leave a Reply

Your email address will not be published. Required fields are marked *