javascriptcharacter-entities

Convert HTML Character Entities back to regular text using javascript


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.


Solution

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