js 实现 unicode
Unicode 编码与解码
在 JavaScript 中,Unicode 可以通过多种方式处理,包括字符串字面量、转义序列和 API 方法。
字符串中使用 Unicode 直接使用 Unicode 字符:
const str = '你好'; // 直接包含 Unicode 字符
使用 Unicode 转义序列(\uXXXX 格式):
const str = '\u4F60\u597D'; // "你好" 的 Unicode 转义
编码转换 将字符串转换为 Unicode 编码数组:
function toUnicode(str) {
return Array.from(str).map(char =>
'\\u' + char.charCodeAt(0).toString(16).padStart(4, '0')
).join('');
}
console.log(toUnicode('你好')); // 输出 \u4f60\u597d
解码 Unicode 转义序列
将 \uXXXX 格式的字符串转换为实际字符:
function decodeUnicode(str) {
return str.replace(/\\u[\dA-F]{4}/gi,
match => String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16))
);
}
console.log(decodeUnicode('\\u4f60\\u597d')); // 输出 "你好"
处理高位 Unicode(代理对)
对于超出 BMP(基本多语言平面)的字符(如表情符号),需要使用代理对处理:
检查是否为代理对
function isSurrogatePair(char) {
const code = char.charCodeAt(0);
return code >= 0xD800 && code <= 0xDBFF;
}
完整 Unicode 编码获取
function getFullUnicode(str) {
let result = [];
for (let i = 0; i < str.length; i++) {
const high = str.charCodeAt(i);
if (isSurrogatePair(str[i])) {
const low = str.charCodeAt(++i);
const code = (high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000;
result.push('\\u{' + code.toString(16) + '}');
} else {
result.push('\\u' + high.toString(16).padStart(4, '0'));
}
}
return result.join('');
}
console.log(getFullUnicode('😊')); // 输出 \u{1f60a}
ES6+ 特性
现代 JavaScript 提供更简洁的 Unicode 支持:
码点 API
'😊'.codePointAt(0).toString(16); // 返回 "1f60a"
String.fromCodePoint(0x1F60A); // 返回 "😊"
Unicode 正则支持
/\p{Emoji}/u.test('😊'); // true
字符串迭代 正确处理代理对:
[...'a😊b'].length; // 3(传统方法会返回4)
注意事项
- 避免混淆
charCodeAt(UTF-16 编码单元)和codePointAt(完整码点) - 处理网络传输时确保字符编码声明为 UTF-8
- 文件保存时使用 UTF-8 编码以避免乱码







