How do I escape some html in javascript?

Micah picture Micah · Mar 9, 2011 · Viewed 41.8k times · Source

Given the text

<b>This is some text</b>

I want to write it to my page so that it shows up like this:

<b>This is some text</b>

and not like this

This is some text

using escape("<b>This is some text</b>") gives me this lovely gem in firefox

%3Cb%3EThis%20is%20some%20text%3C/b%3E

not exaclty what I'm after. Any ideas?

Answer

limc picture limc · Mar 9, 2011

This should work for you: http://blog.nickburwell.com/2011/02/escape-html-tags-in-javascript.html

function escapeHTML( string )
{
    var pre = document.createElement('pre');
    var text = document.createTextNode( string );
    pre.appendChild(text);
    return pre.innerHTML;
}

Security Warning

The function doesn't escape single and double quotes, which if used in the wrong context, may still lead to XSS. For example:

 var userWebsite = '" onmouseover="alert(\'gotcha\')" "';
 var profileLink = '<a href="' + escapeHtml(userWebsite) + '">Bob</a>';
 var div = document.getElemenetById('target');
 div.innerHtml = profileLink;
 // <a href="" onmouseover="alert('gotcha')" "">Bob</a>

Thanks to buffer for pointing out this case. Snippet taken out of this blog post.