Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I escape some html in javascript?

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?

like image 567
Micah Avatar asked Mar 09 '11 20:03

Micah


People also ask

Can I escape HTML special characters in JavaScript?

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.

How do you escape characters in JavaScript?

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)


1 Answers

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.

like image 126
limc Avatar answered Oct 09 '22 02:10

limc