JavaScript Intl.Segmenter: Words and Grapheme Clusters
Quick answer
Intl.Segmenter divides text into locale-sensitive segments such as grapheme clusters, words or sentences. It helps avoid treating every UTF-16 code unit as a visible character.
How it works
Create new Intl.Segmenter(locale,{granularity:"grapheme"}) and iterate over segment(text). Each record includes segment, index and input; word segmentation can also report isWordLike. Indices are UTF-16 offsets. containing(index) finds the segment covering a code-unit position. Use supported locales and note that Unicode and dictionary data may differ.
const text="é😀"; const s=new Intl.Segmenter("en",{granularity:"grapheme"}); console.log(text.length,[...text].length,[...s.segment(text)].length);Expected output in Node.js:
4 3 2The combining sequence and emoji are two grapheme clusters.
const s=new Intl.Segmenter("en",{granularity:"word"}); console.log([...s.segment("tea, cake!")].filter(x=>x.isWordLike).map(x=>x.segment).join("|"));Expected output in Node.js:
tea|cakeWord-like filtering excludes punctuation and spacing.
Common mistakes
Using spread counts code points, not necessarily grapheme clusters. Word segmentation includes punctuation and whitespace records, so filter by isWordLike when appropriate.
Practice
Count grapheme clusters in a short string in a supported local runtime.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Intl.Segmenter: Words and Grapheme Clusters — Knowledge Check
Apply the taught concept and predict the output.
Which granularity approximates user-perceived character boundaries?
What unit is a segment record index measured in?
How can you filter word segmentation to word-like items?
What is the exact console output in JavaScript Intl.Segmenter: Words and Grapheme Clusters example 1?
const text="é😀"; const s=new Intl.Segmenter("en",{granularity:"grapheme"}); console.log(text.length,[...text].length,[...s.segment(text)].length);What is the exact console output in JavaScript Intl.Segmenter: Words and Grapheme Clusters example 2?
const s=new Intl.Segmenter("en",{granularity:"word"}); console.log([...s.segment("tea, cake!")].filter(x=>x.isWordLike).map(x=>x.segment).join("|"));