← 中文资源

简体中文版本

用 Intl.Segmenter 计数字形

用 Intl.Segmenter 按字形计数:组合重音符、多码点 emoji 各算一个字形,length 的码元数与用户感知字符数可以差出好几倍,换 granularity 还能按词切分。

阅读英文原文

实现说明

整个示例围绕函数 countGraphemes组织。 结果是全新构造,调用方可以放心保留自己的原件。

使用要点

  • 每一步打印都带着自己的标签:composed length:、decomposed length:、both grapheme counts:。

常见问题

countGraphemes 会修改传入的参数吗?

不会。传入的任何东西都不会被写入,对共享数据调用是安全的。

包管理器会看到什么?

一份空的依赖清单。示例没有需要抓取的导入。 文件在加载时定义 countGraphemes。

主要签名是 function countGraphemes(text)

核心语句

const segmenter = new Intl.Segmenter('en', { granularity: 'grapheme' });
const wordSegmenter = new Intl.Segmenter('en', { granularity: 'word' });
return [...segmenter.segment(text)].length;

代码示例

const segmenter = new Intl.Segmenter('en', { granularity: 'grapheme' });

function countGraphemes(text) {
  return [...segmenter.segment(text)].length;
}

// length 按 UTF-16 码元计数:拆开的重音符会多出一个码元,字形计数两者一致
const cafeComposed = 'café';
const cafeDecomposed = 'cafe\u0301';
console.log('composed length:', cafeComposed.length);
console.log('decomposed length:', cafeDecomposed.length);
console.log('both grapheme counts:', countGraphemes(cafeComposed), countGraphemes(cafeDecomposed));

// 多码点合成的 emoji:一个字形、多个码点
const family = '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F466}';
console.log('family units:', family.length, 'graphemes:', countGraphemes(family));

// 同一个 API 换 granularity 即可按词切分:locale 感知,比 split(' ') 可靠
const wordSegmenter = new Intl.Segmenter('en', { granularity: 'word' });
const words = [...wordSegmenter.segment('deploy the cache-invalidation fix')]
  .filter((part) => part.isWordLike)
  .map((part) => part.segment);
console.log('words:', words.join('|'));