js 实现 unicode
Unicode 编码与解码
在 JavaScript 中,字符串是基于 Unicode 编码的,可以直接处理 Unicode 字符。以下是常见的 Unicode 操作方法:
直接使用 Unicode 字符
JavaScript 字符串可以直接包含 Unicode 字符:
const str = '你好世界'; // 直接使用 Unicode 字符
使用 Unicode 转义序列
通过 \u 前缀加上 4 位十六进制数表示 Unicode 字符:
const str = '\u4F60\u597D\u4E16\u754C'; // "你好世界"
获取字符的 Unicode 编码
使用 charCodeAt() 方法获取字符的 UTF-16 编码(0-65535):
'A'.charCodeAt(0); // 65
对于超出 BMP(基本多语言平面)的字符(如 emoji),使用 codePointAt():
'😊'.codePointAt(0); // 128522
从 Unicode 编码生成字符
使用 String.fromCharCode() 从 UTF-16 编码生成字符:
String.fromCharCode(65); // "A"
对于高位 Unicode 编码(> 0xFFFF),使用 String.fromCodePoint():
String.fromCodePoint(128522); // "😊"
处理代理对
高位 Unicode 字符(如 emoji)在 UTF-16 中由代理对表示:
const emoji = '😊';
emoji.length; // 2(代理对占用 2 个码元)
[...emoji].length; // 1(扩展运算符能正确识别)
正则表达式与 Unicode
启用 u 标志使正则表达式支持 Unicode:
/^\u{1F600}$/u.test('😀'); // true
字符串迭代
使用 for...of 或扩展运算符可正确迭代 Unicode 字符:
for (const char of '👨👩👧👦') {
console.log(char); // 正确输出每个字符(包括组合字符)
}
常见编码转换
转换为 UTF-8 字节数组:
function encodeUTF8(str) {
return new TextEncoder().encode(str);
}
encodeUTF8('你好'); // Uint8Array [228, 189, 160, 229, 165, 189]
从 UTF-8 解码:

function decodeUTF8(bytes) {
return new TextDecoder().decode(bytes);
}
decodeUTF8(new Uint8Array([228, 189, 160, 229, 165, 189])); // "你好"
注意事项
- JavaScript 内部使用 UTF-16 编码字符串
- 高位字符(如 emoji)会占用两个码元(
length为 2) - 使用
codePointAt()和fromCodePoint()处理高位字符更可靠 - 现代浏览器已全面支持 Unicode 13.0+ 标准






