JavaScript
Count grapheme clusters in a string
Use Intl.Segmenter with grapheme granularity when counting user-perceived text units. String.length counts UTF-16 code units, which can split emoji and combining-character sequences.
Worked example
Node.js example · save as example.mjs and run node example.mjs
const text = "A\u{1F469}\u200d\u{1F4BB}e\u0301";
const segmenter = new Intl.Segmenter("en", {granularity: "grapheme"});
console.log(text.length);
console.log([...segmenter.segment(text)].length);How it works
The example contains A, a woman-technologist emoji sequence, and an e with a combining accent. Segmenter treats those sequences as three grapheme clusters. This is useful for text counters where a simple code-unit limit would confuse users.
Limits and mistakes
Grapheme count is not byte length, display width, or a guarantee about how every font renders text. Unicode segmentation rules and runtime support matter. Storage and protocol limits should use the units those systems actually enforce.
Check the result
Expect a code-unit count larger than three and a grapheme count of three. Add flags, skin-tone emoji, and combining marks when checking a user-facing character limit.
Sources
Reference documentation for the behavior used in this guide: