chujiamo.PERSONAL COLLECTION · 001

文本长度与 UTF-8 字节数

用「楚」和一个表情看清 JavaScript 字符串长度、Unicode 码点和 UTF-8 字节数。

JavaScript · UTF-8

技术笔记 · 可用编解码工作台复现。

在 JavaScript 里,字符串的 length 统计 UTF-16 代码单元,字符串迭代按 Unicode 码点前进。将字符串写成 UTF-8 时,每个码点又会占用不同数量的字节。

输入 UTF-16 代码单元 Unicode 码点 UTF-8 字节
A 1 1 1
楚 1 1 3
🎵 2 1 4

查看字节

const text = "楚🎵";
const codePoints = Array.from(text).length;
const bytes = new TextEncoder().encode(text);
console.log(text.length, codePoints, bytes.length); // 3, 2, 7

在编解码工作台选择十六进制,输入 楚🎵 后可以看到 e6 a5 9a f0 9f 8e b5,每一对十六进制数字代表一个字节。