除了使用一个回调函数,你可能要考虑为十六进制字符引用添加支持(ሴ
)。
此外,fromCharCode
可能不够。例如𐤀
是对腓尼基字符的有效引用,但由于它位于基本多语言平面之外,并且JavaScript的字符串模型基于UTF-16代码单元,而不是完整的字符代码点,因此fromCharCode(67840)
将不起作用。你需要一个UTF-16编码器,例如:
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 𐤀!'));
这只是返回``foos bar“`。我错过了什么吗?编辑:哦,显然这是因为`match` =`“'”`而不仅仅是`39`。 – alfonso 2010-11-27 15:23:17
是的,你是正确的,我修复了代码从此 – 2010-11-27 15:25:48