JavaScript 中的 Unicode 转字符主要涉及到两个函数:String.fromCharCode()
和 String.prototype.charCodeAt()
。
String.fromCharCode()
:String.prototype.charCodeAt()
:U+0000
到 U+FFFF
。U+10000
到 U+10FFFF
,这些字符需要两个 UTF-16 代码单元来表示。原因:某些 Unicode 字符(如 emoji)需要两个 UTF-16 代码单元来表示,这可能导致在处理字符串时出现问题。
解决方法:
function getUnicodeChar(str, index) {
let code = str.charCodeAt(index);
if (code >= 0xD800 && code <= 0xDBFF && index + 1 < str.length) {
let nextCode = str.charCodeAt(index + 1);
if (nextCode >= 0xDC00 && nextCode <= 0xDFFF) {
return String.fromCharCode(((code - 0xD800) * 0x400) + (nextCode - 0xDC00) + 0x10000);
}
}
return String.fromCharCode(code);
}
let str = "😊"; // U+1F60A
console.log(getUnicodeChar(str, 0)); // 😊
这个函数可以正确处理代理对字符,确保即使是复杂的 Unicode 字符也能被正确解析。
通过这种方式,开发者可以更有效地处理和操作 Unicode 字符,确保应用程序能够正确显示和处理各种语言和特殊字符。
领取专属 10元无门槛券
手把手带您无忧上云