How to get char from HTML character code?

[亡魂溺海] 提交于 2019-12-07 05:43:54

问题


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


回答1:


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.




回答2:


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); // € ► ♠ " &



回答3:


document.getElementById("myElement").innerHTML = "&#8364".fromCharCode();

Actually, scratch that, the fromCharCode() function is only available on the String object, so it would look like what Will Morgan said:

document.getElementById("myElement").innerHTML = String.fromCharCode(8364)


来源:https://stackoverflow.com/questions/10253880/how-to-get-char-from-html-character-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!