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?
We can use the textContent property of the HTML Textarea element and insert the HTML string. After that, we can get encoded string with Unicode using the innerHTML property.
Javascript uses '\' (backslash) in front as an escape character. To print quotes, using escape characters we have two options: For single quotes: \' (backslash followed by single quote) For double quotes: \” (backslash followed by double quotes)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With