How can I convert the HTML entities € ► ♠
to their actual characters € ► ♠
using JavaScript?
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.
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); // € ► ♠ " &
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With