5
4

3 回答 3

11

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.

于 2012-04-20T21:40:20.483 回答
3

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); // € ► ♠ " &
于 2012-04-20T22:55:43.580 回答
2
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)
于 2012-04-20T21:38:26.040 回答