JavaScript 字符串 length 与字符数的区别:如何计算表情长度

JavaScript 的 text.length 计算 UTF-16 码元数。🙂 有两个码元,但只有一个码点和一个可见的字符组。用 Intl.Segmenter 统计可见字符组,用 TextEncoder 统计 UTF-8 字节。

用 length 计算 UTF-16 码元

length 是属性,读取时无需括号。UTF-16(16 位 Unicode 转换格式)用 16 位码元表示文本。运行代码可以看到空格也计数,空字符串的长度为 0。字符串不可变,给 length 赋值无法截短字符串。参见 ECMAScript: String Type。

console.log('abcd'.length); // 4
console.log('\uD55C\uAE00'.length); // 2
console.log(''.length);     // 0
console.log('a b'.length);  // 3

计算表情符号和组合字符的码点

Array.from(text).length 计算字符串迭代器读出的码点数。🙂 的代理对计为一个码点。e\u0301 含有基础字母和组合重音符两个码点。

const face = String.fromCodePoint(0x1F642);
console.log(face.length);             // 2
console.log(Array.from(face).length); // 1
const accented = 'e\u0301';
console.log(accented.length);             // 2
console.log(Array.from(accented).length); // 2

区分字素簇与 UTF-8 字节的用途

字素簇通常指用户感知为一个字符的单位。使用 granularity: 'grapheme' 时,Intl.Segmenter 会将 A🙂é 计为三个字素簇。代码用 typeof 检查支持情况。缺少分割功能时会显示提示,码点数仍单独显示。参见 Intl.Segmenter。

const sample = 'A' + String.fromCodePoint(0x1F642) + 'e\u0301';
console.log(sample.length);            // 5
console.log(Array.from(sample).length); // 4

if (typeof Intl.Segmenter === 'function') {
  const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
  console.log(Array.from(segmenter.segment(sample)).length); // 3
}

console.log(new TextEncoder().encode(sample).length); // 8

如果存储或传输限制以 UTF-8 为单位,用 new TextEncoder().encode(text).length 统计字节。A🙂é 占八字节。请说明限制单位,并在服务器用同一规则验证。参见 Encoding Standard: TextEncoder。

完整示例:输入文本时比较四种长度

将 HTML 以 UTF-8 保存为 string-length.html 并打开。初始文本 A🙂é 有 5 个 UTF-16 码元、4 个码点、3 个字素簇和 8 个 UTF-8 字节。

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>比较四种字符串长度</title>
</head>
<body>
<label for="text">请输入文本</label>
<textarea id="text" rows="3" cols="40">A🙂é</textarea>
<pre id="output" aria-live="polite"></pre>
<script>
const input = document.querySelector('#text');
const output = document.querySelector('#output');
const encoder = new TextEncoder();
const segmenter = typeof Intl.Segmenter === 'function'
  ? new Intl.Segmenter(undefined, { granularity: 'grapheme' }) : null;

function render() {
  const value = input.value;
  const points = Array.from(value).length;
  const graphemes = segmenter
    ? Array.from(segmenter.segment(value)).length : "此环境不支持";
  output.textContent = `UTF-16 码元数: ${value.length}\n` +
    `码点数: ${points}\n` +
    `字素簇数: ${graphemes}\n` +
    `UTF-8 字节数: ${encoder.encode(value).length}`;
}

input.addEventListener('input', render);
render();
</script>
</body>
</html>

改为仅输入 👩‍💻,四个结果依次是 5、3、1 和 11。多个码点也能组成一个可见的表情。清空输入后,支持的计数均为 0。如果不支持分割,相应行会显示提示。