Espen Hovlandsdal
Written by Espen Hovlandsdal
Published 2012-03-16

Strip HTML from a string in Javascript

Should you need to strip HTML from a string (say you are building a chunk of HTML and need to insert the content of an input-field into it), this is a simple way of doing it:

Entry image

Quick tip; never use innerHTML (or jQuery’s html()) unless you really want to insert HTML.
Quite often, what you actually want is to insert some text. If this is the case, use innerText (or jQuery’s text()).

Or, if you’re using jQuery:

WARNING: Please be aware that any code (script tags) and resources linked (images, scripts) will still be run using this approach. Only use this approach when you have some degree of control over the input and context. Securing markup is not a trivial task and should be given more thought.

Written by Espen Hovlandsdal
Published 2012-03-16