Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get char from HTML character code?

How can I convert the HTML entities € ► ♠ to their actual characters € ► ♠ using JavaScript?

like image 625
Danny Fox Avatar asked Apr 20 '12 21:04

Danny Fox


2 Answers

An example would be: alert(String.fromCharCode(8364));

Where 8364 is the number of the HTML entity.

To replace a full body of text automatically then you will need to use this regular expression replacement example:

"The price of milk is now €100000.".replace(/&#(\d{0,4});/g, function(fullStr, str) { return String.fromCharCode(str); });

The magic happens here:

replace(/&#(\d{1,4});/g, function(fullStr, code) { return String.fromCharCode(code); });

The first argument to replace, /&#(\d{1,4});/g, specifies 1 to 4 digits surrounded by &# and ; respectively. The second parameter, function(fullStr, code) [...] does the replacement, where code is the digits.

like image 181
Will Morgan Avatar answered Oct 02 '22 04:10

Will Morgan


You could use the browser's built-in HTML parser via innerHTML, which will have the advantage of handling all HTML entities, not just numeric ones. Note that the following will not work if the string passed to the function contains HTML tags.

function convertEntities(html) {
    var el = document.createElement("div");
    el.innerHTML = html;
    return el.firstChild.data;
}

var html = "€ ► ♠ " &";
var text = convertEntities(html); // € ► ♠ " &
like image 22
Tim Down Avatar answered Oct 02 '22 03:10

Tim Down