As well as using a callback function, you may want to consider adding support for hex character references (ሴ
).
Also, fromCharCode
may not be enough. eg 𐤀
is a valid reference to a Phoenician character, but because it is outside the Basic Multilingual Plane, and JavaScript's String model is based on UTF-16 code units, not complete character code points, fromCharCode(67840)
won't work. You'd need a UTF-16 encoder, for example:
String.fromCharCodePoint= function(/* codepoints */) {
var codeunits= [];
for (var i= 0; i<arguments.length; i++) {
var c= arguments[i];
if (arguments[i]<0x10000) {
codeunits.push(arguments[i]);
} else if (arguments[i]<0x110000) {
c-= 0x10000;
codeunits.push((c>>10 & 0x3FF) + 0xD800);
codeunits.push((c&0x3FF) + 0xDC00);
}
}
return String.fromCharCode.apply(String, codeunits);
};
function decodeCharacterReferences(s) {
return s.replace(/&#(\d+);/g, function(_, n) {;
return String.fromCharCodePoint(parseInt(n, 10));
}).replace(/&#x([0-9a-f]+);/gi, function(_, n) {
return String.fromCharCodePoint(parseInt(n, 16));
});
};
alert(decodeCharacterReferences('Hello 𐤀 mum 𐤀!'));