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?
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
This worked stunningly, where jQuery was locking up. You are my hero for the day!
For some reason this returns null when changing the enctype of a form from multipart/form-data in Chrome
That code worked flawlessly. Genius. Thanks!
Regards,
Ardee Aram
Sos un genio!!! Estoy hace 2 dias con este problema. THANKS!!!!
NEVER, NEVER *EVER* extend build in Objects. It will Fail. Not at your place maybe, but somewhere.
thanks for the sharing , nice script :D
Hmm this solution doesn’t seem to work for multi-line (separated by \n’s) values.
Thanks. I think that is the better way to make this.
Worked like a charm. Thanks.
Thanks man, very nice !
Superb!
Done with Mootools! Thanks!
Do not use this code with untrusted input! This sample code is a giant XSS vulnerability.
Don’t use any code with untrusted input.
This WON’T work if you are using ie8 and trying to parse data while preserving newline chars as innerHTML will strip those chars out
Excellent script, saved my day thanks a lot.
Read through the below stack overflow answer from lucascaro, apparently this is subject to XSS attacks, which he has a resolution for.
http://stackoverflow.com/questions/1147359/how-to-decode-html-entities-using-jquery