Codectionary / Developer documentation / JavaScript

Grapheme Segmentation with Intl.Segmenter

Intl.Segmenter finds language-aware grapheme, word, or sentence boundaries. Grapheme segmentation is useful for user-perceived characters that consist of several Unicode code points. Availability is newer than basic Intl formatting, so feature-detect it when supporting older runtimes.

Syntax

new Intl.Segmenter("en", { granularity: "grapheme" }).segment(text);

Examples

Grapheme Segmentation with Intl.Segmenter: working example

Run this standalone example in a modern browser console unless another environment is specified. Expected result: The console prints 4 3 2, then é | šŸ™‚.

const text = "eĢšŸ™‚";
const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
const characters = Array.from(segmenter.segment(text), item => item.segment);
console.log(text.length, [...text].length, characters.length);
console.log(characters.join(" | "));
  1. Expected result: The console prints 4 3 2, then é | šŸ™‚.
  2. length counts UTF-16 code units; spreading the string counts Unicode code points.
  3. The combining accent belongs to the e grapheme, so users perceive two characters.

Best practices

  • Use grapheme boundaries when truncating user-visible text.
  • Do not use grapheme counts where a protocol specifies byte or code-unit limits.

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading