JavaScript: how to unescape HTML entities

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;
}

And the code in action:

var hello = "Hello José";
alert(hello.unescapeHtml());

3 Responses to “JavaScript: how to unescape HTML entities”

  1. SSN Says:

    Thanks, Saved my day

  2. Jan Stastny Says:

    Very nice, thanks for posting it. It helped to solve my problem.

  3. Mircea Says:

    very good solution!

Leave a Reply