Convert HTML Character Entities back to regular text using javascript

nuaavee picture nuaavee · Dec 2, 2010 · Viewed 28.4k times · Source

the questions says it all :)

eg. we have >, we need > using only javascript

Update: It seems jquery is the easy way out. But, it would be nice to have a lightweight solution. More like a function which is capable to do this by itself.

Answer

Gumbo picture Gumbo · Dec 2, 2010

You could do something like this:

String.prototype.decodeHTML = function() {
    var map = {"gt":">" /* , … */};
    return this.replace(/&(#(?:x[0-9a-f]+|\d+)|[a-z]+);?/gi, function($0, $1) {
        if ($1[0] === "#") {
            return String.fromCharCode($1[1].toLowerCase() === "x" ? parseInt($1.substr(2), 16)  : parseInt($1.substr(1), 10));
        } else {
            return map.hasOwnProperty($1) ? map[$1] : $0;
        }
    });
};