12k
All articles

Counting Words and Characters with Intl.Segmenter

Count visible characters, words, and sentences with JavaScript Intl.Segmenter. Handle emoji, locale-aware text, and safe truncation in a grapheme-aware textarea counter.

OpenReplay Team
OpenReplay Team
Counting Words and Characters with Intl.Segmenter

Intl.Segmenter is the built-in JavaScript API for splitting text into the characters, words, and sentences a reader actually sees, so emoji and non-English text count correctly where String.prototype.length gets it wrong.

A comment box reports 2 characters after a user types one 👍. A bio field rejects a post that looks well under the limit. A preview truncates a family emoji into separate faces. These bugs share one cause: the code counts how the string is stored, not what appears on screen. This article shows where .length and spread syntax break down, then uses Intl.Segmenter to count graphemes, words, and sentences, handle locales without spaces, and build a working textarea counter.

Key Takeaways

  • String.prototype.length counts UTF-16 code units, so "👍".length is 2 and the family emoji 👨‍👩‍👧‍👦 has a length of 11.
  • Spreading a string with [...str] counts code points. That fixes surrogate pairs, but the family emoji still counts as 7.
  • new Intl.Segmenter(locale, { granularity: "grapheme" }) counts user-perceived characters, so the family emoji and the 🇯🇵 flag each count as 1.
  • With granularity: "word", only segments where isWordLike is true are words. Spaces and punctuation are excluded.
  • To truncate safely, slice an array of grapheme segments and never slice the string by index.

The Problem: .length Miscounts Emoji

In JavaScript, String.prototype.length returns the number of UTF-16 code units in a string. That number often differs from the number of characters a person sees.

const thumbs = "\u{1F44D}";                                                    // 👍
const japan  = "\u{1F1EF}\u{1F1F5}";                                           // 🇯🇵
const family = "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}\u{200D}\u{1F466}"; // 👨‍👩‍👧‍👦

thumbs.length; // 2
japan.length;  // 4
family.length; // 11

The test strings use escapes because copying emoji between editors can silently drop the joiners. A 280-character limit enforced with text.slice(0, 280) can also cut a character in half. A smaller limit shows the same failure:

const msg = "Hi \u{1F44D}"; // "Hi 👍", length 5
msg.slice(0, 4);            // "Hi \uD83D", a lone high surrogate that renders as �

The HTML maxlength attribute has the same blind spot. The WHATWG spec measures maxlength in UTF-16 code units, not in visible characters.

How Does UTF-16 Store Emoji?

JavaScript strings are sequences of 16-bit code units, and MDN’s length reference confirms that the property counts those units. Any code point above U+FFFF, which includes most emoji, is stored as a surrogate pair of two units, so 👍 has a length of 2. Many emoji are also sequences of several code points. The family emoji is four people joined by three zero-width joiners (U+200D). A flag is two regional indicator symbols. A skin-tone emoji is a base code point followed by a modifier. For more on how emoji are encoded in markup, see HTML entities, diacritical marks, and emojis.

Why […str].length Is Not Enough

Spreading a string with [...str] splits it into Unicode code points. That fixes emoji stored as surrogate pairs, but any emoji built from several code points still counts as more than one character.

[...thumbs].length; // 1
[...japan].length;  // 2
[...family].length; // 7

Spread works for single-code-point emoji. Flags, skin tones, and ZWJ sequences still over-count.

How Do You Count Visible Characters in JavaScript?

Intl.Segmenter with granularity: "grapheme" splits text into grapheme clusters, the units a person reads as single characters. The family emoji counts as 1 even though its .length is 11. If you omit granularity, the constructor defaults to "grapheme".

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

const countGraphemes = (text) => {
  let n = 0;
  for (const _ of graphemes.segment(text)) n++;
  return n;
};

countGraphemes(family); // 1
countGraphemes(japan);  // 1

segment() returns an iterable Segments object. Each item has segment, index, and input properties. The for...of loop counts segments without building an intermediate array.

String.length[...s].lengthGraphemes
👍 \u{1F44D}211
🇯🇵 \u{1F1EF}\u{1F1F5}421
👋🏽 \u{1F44B}\u{1F3FD}421
👨‍👩‍👧‍👦 family (ZWJ)1171

Counting Words with isWordLike

When an Intl.Segmenter uses granularity: "word", each segment has an isWordLike boolean. It is true for words, including numbers, and false for spaces and punctuation. Counting only the word-like segments gives an accurate word count.

const words = new Intl.Segmenter("en", { granularity: "word" });

const countWords = (text) => {
  let n = 0;
  for (const { isWordLike } of words.segment(text)) if (isWordLike) n++;
  return n;
};

countWords("Hello, world! It's 2 o'clock."); // 5

The five words are Hello, world, It's, 2, and o'clock. The Unicode word-boundary rules in UAX #29 keep an apostrophe between letters inside the word. The comma, the exclamation mark, the period, and the spaces each become non-word segments.

Splitting Sentences

Intl.Segmenter with granularity: "sentence" splits text at sentence boundaries. Each segment keeps its trailing whitespace. The rules are heuristic, so abbreviations can cause a split too early.

const sentences = new Intl.Segmenter("en", { granularity: "sentence" });

[...sentences.segment("Dr. Smith arrived. He sat down.")].map((s) => s.segment);
// ["Dr. ", "Smith arrived. ", "He sat down."]

UAX #29 suppresses a break after a period only when a lowercase letter follows. Here “Smith” is capitalised, so “Dr.” ends up as a sentence of its own. Treat sentence counts as approximate, and test against real content from your users before you show them.

Locale Matters: Japanese and Thai

split(" ") cannot find words in Japanese, Chinese, or Thai because those languages don’t put spaces between words. A word segmenter created with the matching locale applies that language’s break rules.

const ja = "吾輩は猫である。名前はたぬき。";

ja.split(" ");
// ["吾輩は猫である。名前はたぬき。"]

[...new Intl.Segmenter("ja-JP", { granularity: "word" }).segment(ja)]
  .filter((s) => s.isWordLike)
  .map((s) => s.segment);
// ["吾輩", "は", "猫", "で", "ある", "名前", "は", "たぬき"]

MDN’s constructor page documents this segmentation. It produces eight words, with each 。 flagged as not word-like. Unfamiliar words such as product names can be split in unexpected places, so check the output in the browsers you target.

A Grapheme-Aware Textarea Counter

The textarea counter below creates one segmenter per granularity at module scope and reuses both in the input handler, so it does not construct new objects on every keystroke.

<textarea id="bio" rows="4" cols="40"></textarea>
<p id="count"></p>
<script>
  const LIMIT = 280;
  const g = new Intl.Segmenter(navigator.language, { granularity: "grapheme" });
  const w = new Intl.Segmenter(navigator.language, { granularity: "word" });

  const bio = document.getElementById("bio");
  const out = document.getElementById("count");

  bio.addEventListener("input", () => {
    let chars = 0;
    let wordCount = 0;
    for (const _ of g.segment(bio.value)) chars++;
    for (const s of w.segment(bio.value)) if (s.isWordLike) wordCount++;
    out.textContent = `${chars}/${LIMIT} characters · ${wordCount} words`;
    out.style.color = chars > LIMIT ? "crimson" : "";
  });
</script>

The handler does not rewrite bio.value, because changing the value programmatically moves the caret. Show the over-limit state while the user types, and truncate when generating a preview or on submit.

To truncate without breaking an emoji, slice an array of grapheme segments, not the string. Reserve one grapheme for a single-character ellipsis (U+2026) so the result never goes over max. Appending "..." after cutting to max would add three characters past a hard limit.

function truncate(text, max) {
  const parts = [...g.segment(text)];
  if (parts.length <= max) return text;
  return parts.slice(0, max - 1).map((p) => p.segment).join("") + "…";
}

const wave = "Hi \u{1F44B}\u{1F3FD} there";
wave.slice(0, 5);    // "Hi 👋" (skin-tone modifier lost)
truncate(wave, 5);   // "Hi 👋🏽…" (5 graphemes)

Intl.Segmenter has worked in all major browsers since April 2024, when Firefox 125 shipped. It became Baseline Widely available on 16 October 2026. The same code runs in Node because official Node.js builds include full ICU data.

Conclusion

Count what the reader sees. Use a grapheme segmenter for character limits, isWordLike for word counts, and the user’s locale for languages written without spaces. Next, find every .length, slice(), and maxlength check that enforces a user-facing limit and replace it with a reused segmenter. Intl.Segmenter belongs to the same Intl family as the APIs covered in formatting dates and numbers with the Intl API.

FAQs

What happens if Intl.Segmenter does not support the locale I pass?

It falls back to the runtime's default locale without throwing an error. Call Intl.Segmenter.supportedLocalesOf(['th', 'ja-JP']) to get the requested locales that are supported without fallback, or read segmenter.resolvedOptions().locale to see which locale an instance actually uses. This check matters most for word granularity in languages written without spaces, where the wrong locale changes where words break.

Does Unicode normalization change the grapheme count of a string?

No. An accented letter can be stored precomposed as U+00E9 or decomposed as the letter e followed by the combining acute accent U+0301. The decomposed form has a length of 2 and spreads into 2 code points, but both forms count as 1 grapheme. Calling text.normalize('NFC') changes the length, not the grapheme count, so normalize text for storage and comparison and segment it for counting.

How do I map a grapheme segment back to a cursor position in a textarea?

Use the index property of each segment. It gives the UTF-16 code unit offset where the segment starts in the input string, which is the same unit that selectionStart, selectionEnd and setSelectionRange() use. To find the grapheme at the caret, call segments.containing(textarea.selectionStart). It returns the segment covering that code unit index, or undefined if the index is out of range.

Should the server also enforce character limits with graphemes?

Yes. Client-side checks are easy to bypass, so apply the same rule on the server. Node.js provides the same Intl.Segmenter API, so one counting function can run in both places. Database column limits usually count code points or bytes, not graphemes, so text that passes a 280-grapheme check can still overflow a 280-character column when it contains ZWJ emoji. Give the column headroom or set a separate byte limit.

Open-source session replay

Complete picture for complete understanding

Capture every clue your frontend is leaving so you can instantly get to the root cause of any issue with OpenReplay — the open-source session replay tool for developers. Self-host it in minutes, and have complete control over your customer data.

Star on GitHub12k

We use cookies to improve your experience. By using our site, you accept cookies.