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());

10 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!

  4. Goemr says:

    This looks a lot more like a hack than a clean solution, isn’t it?

  5. Ofer says:

    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

  6. Chris says:

    Could someone explain why temp.removeChild(temp.firstChild) is needed? It seems unnecessary… the JS engine should just garbage collect all that, right?

  7. Pingback: johnjcamilleri.com » How to unescape HTML entities in JavaScript

  8. Shelby says:

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

  9. dadoo says:

    thanks a lot Paul
    nice, elegant and perfect

  10. Michael says:

    Lifesaver! Thanks Paul

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>