除了使用一個回調函數,你可能要考慮爲十六進制字符引用添加支持(ሴ
)。
此外,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