Experiences on the Front Lines of User Interfaces and Web Development

Escape HTML tags in Javascript

If you need to display text to a user, you most likely want to escape the string so that HTML is not rendered. This is good practice for security, but also prevents you from mangling or hiding important characters in a string (such as if the user typed "my <name>"... we wouldn't want the browser to treat <name> as a HTML tag).

Whenever possible, the server should do the escaping of strings. But sometimes there comes an occasion (usually in an ajax-heavy, edit-in-place type UI) where you will need to escape HTML client-side.  Javascript doesn't have a built in method for doing that (they have escape, and encodeURI, but those are for escaping URLs and URL parameters).  What you want is a function that takes "<", ">", etc and converts them to "&lt;", "&gt;", etc.

Below is a clever function that does the trick for you, without the need for regex's:
function escapeHTML( string )
var pre = document.createElement('pre');
var text = document.createTextNode( string );
return pre.innerHTML;

If you are using jQuery, you can do this instead:
function escapeHTML( string )
return jQuery( '<pre>' ).text( string ).html();


Notice the use of a <pre> tag, rather than the more popular <div>.  This is because IE does not preserve whitespace when you create a text node inside a div, so if you want to preserve newlines, stick with the <pre> tag.  http://api.jquery.com/text/#comment-30080940


Ondřej Medek
Very nice solution. Thanks.

comments powered by Disqus