comments (not for humans)
You may sometimes need to unescape HTML escaped strings in javascript. I found a neat trick to do this using the browser internal escaping.

This entry in the blog ecmanaut presents a neat way to unescape HTML without calling homebrewed methods replacing each character. Using this I created the following javascript function:

function unescapeHTML(html) {
var htmlNode = document.createElement("DIV");
htmlNode.innerHTML = html;
if(htmlNode.innerText !== undefined)
return htmlNode.innerText; // IE
return htmlNode.textContent; // FF
}
Update 2007-07-07: Added HG's version which should work properly in both IE and FF
Update: Adding Marcus Phillips suggestion for testing against undefined

jQuery versions for both ways

Update 2010-04-28:function unescapeHTML(html) {
return $("<div />").html(html).text();
}
function escapeHTML(html) {
return $("<div />").text(html).html();
}

Brian Ritchie

Doesn't work with Firefox

Using Firefox 1.5.0.4, it results in a value of "undefined"
Dud

Thank you!

very clever trick! thank youthankyou
HG

Works

In IE and Firefox:

function unescapeHTML(html) {
var htmlNode = document.createElement("DIV");
htmlNode.innerHTML = html;
if(htmlNode.innerText)
return htmlNode.innerText; // IE
return htmlNode.textContent; // FF

}
Erlend

Re: Works

Thanks. I'll update
Rob Hildyard
Cheers for this!
Mario Di Vece

Great!

Thanks so much. very useful! I spent almost an hour scratching my head on the option.innerHTML bug in IE.
Starkom

bug

It doesn\'t work in Mozilla 1.7 :(
Starkom

bug

Because problems in Mozilla, I tried such variant:
function unescapeHTML(html) {
var htmlNode = document.createElement(\"DIV\");
htmlNode.innerHTML = html;
return htmlNode.innerHTML;
}
And all looks fine. Is this any wrong?
EdU

THANKS!!!!

THANKS! THANKS! VERY USEFUL!
Noah

Thank you so much!

Just saved me writing a big switch statement... Clever!
Marcus Phillips

BUGFIX for whitespace rendering as "undefined"

If the content you want to translate is whitespace only, it will collapse to an empty string and evaluate to false in the browser-agent detection, causing IE to erroneously check the .textContent variable.

Instead of testing for truthiness, test for existence:

function unescapeHTML(html) {
var htmlNode = document.createElement("DIV");
htmlNode.innerHTML = html;
if(htmlNode.innerText !== undefined)
return htmlNode.innerText; // IE
return htmlNode.textContent; // FF
}
Jim
Great! Thanks a lot!
Akash

thanks mate

godlike :)
Akash

Java Method

public String unescapeHTML(String html) {
com.google.gwt.dom.client.Element htmlNode = DOM.createElement(\"DIV\");
htmlNode.setInnerHTML(html);
return htmlNode.getInnerText();
}
do
gre=unescape("%72%69%6D%62%61%75%64"); what does it mean?
user

Nice job...

...helped me a lot! Thx...
TheHuge_
Thanks a lot!
Comments closed for this post