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?
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.