Count Graphemes With Intl Segmenter

Count user-perceived characters with Intl.Segmenter grapheme segmentation, and switch granularity to word for locale-aware token splitting.

JavascriptData Integrity

Code

javascriptsnippet
23 lines
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('|'));

How it works

Structurally, expect the function countGraphemes and nothing else.

The result is a fresh construction, so callers can keep their originals.

Putting it to use

The main signature reads function countGraphemes(text)

The demo output is labeled (composed length:, decomposed length:, both grapheme counts:), so every printed line maps back to its originating operation.

Core lines

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

Interactive Tools for This Topic

FAQ

Does `countGraphemes` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. The file defines `countGraphemes` at load time.