I was searching the web for JavaScript HTML entity unescaping code. I found lots of really bad ideas. Sound familiar? Some were quite complicated.
It looked like the scriptaculous guys had the right idea. However, all I could find was a cached page with no code. A quick peek inside prototype set me on the right track.
String.prototype.unescapeHtml = function () {
var temp = document.createElement("div");
temp.innerHTML = this;
var result = temp.childNodes[0].nodeValue;
temp.removeChild(temp.firstChild);
return result;
}
var temp = document.createElement("div");
temp.innerHTML = this;
var result = temp.childNodes[0].nodeValue;
temp.removeChild(temp.firstChild);
return result;
}
And the code in action:
var hello = "Hello José";
alert(hello.unescapeHtml());
alert(hello.unescapeHtml());
Thanks, Saved my day
Very nice, thanks for posting it. It helped to solve my problem.
very good solution!
This looks a lot more like a hack than a clean solution, isn’t it?
Thanks for your post, thanks to it I have done the same with jQuery, although the code maybe a little shorter…
Using jQuery, the same can be achieved using
$(“<div>”+string+”</div>”).html()
Kudos
Could someone explain why temp.removeChild(temp.firstChild) is needed? It seems unnecessary… the JS engine should just garbage collect all that, right?
Pingback: johnjcamilleri.com » How to unescape HTML entities in JavaScript
No need to remove the child text node, as the garbage collector (GC memory manager) will.
String.prototype.EntityDecode = function()
{
var t = document.createElement( ‘div’ );
t.innerHTML = this;
return t.firstChild.nodeValue;
}
thanks a lot Paul
nice, elegant and perfect
Lifesaver! Thanks Paul