Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 556
nuaavee Avatar asked Dec 02 '10 19:12

nuaavee


People also ask

How do I convert HTML text to normal text in Java?

Just call the method html2text with passing the html text and it will return plain text.

How do you unescape a character in HTML?

One way to unescape HTML entities is to put our escaped text in a text area. This will unescape the text, so we can return the unescaped text afterward by getting the text from the text area. We have an htmlDecode function that takes an input string as a parameter.


1 Answers

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;
        }
    });
};
like image 118
Gumbo Avatar answered Oct 06 '22 23:10

Gumbo