|
| 1 | +--- |
| 2 | +title: "Intl.Segmenter — String.split Was Wrong, Here's the Fix" |
| 3 | +description: "Counting characters with .length lies on emoji, accents, CJK, and grapheme clusters. Intl.Segmenter is the platform's text-aware segmentation API." |
| 4 | +date: 2026-05-10 |
| 5 | +slug: intl-segmenter |
| 6 | +tags: [javascript, typography] |
| 7 | +--- |
| 8 | + |
| 9 | +```js |
| 10 | +"👨👩👧".length; // 8 |
| 11 | +"naïve".split(""); // ["n", "a", "i", "̈", "v", "e"] — accent split off |
| 12 | +"今日は".split(/\s/); // ["今日は"] — no spaces between Japanese sentences |
| 13 | +``` |
| 14 | + |
| 15 | +JavaScript strings are UTF-16 code units. **One visible character ≠ one code unit.** This breaks `.length`, `.split("")`, character counting, truncation, search, line-breaking. `Intl.Segmenter` is the spec-compliant replacement. |
| 16 | + |
| 17 | +## Counting graphemes, not code units |
| 18 | + |
| 19 | +```js |
| 20 | +const seg = new Intl.Segmenter("en", { granularity: "grapheme" }); |
| 21 | +[...seg.segment("👨👩👧")].length; // 1 — one family emoji |
| 22 | +[...seg.segment("naïve")].length; // 5 — n, a, ï, v, e (composed correctly) |
| 23 | +``` |
| 24 | + |
| 25 | +A grapheme is "one user-perceived character." Family emoji = 1. Combined accent = 1. Tonal mark over Vietnamese = 1. |
| 26 | + |
| 27 | +## Truncating without breaking emoji |
| 28 | + |
| 29 | +The classic "first 40 chars" naive code: |
| 30 | + |
| 31 | +```js |
| 32 | +text.slice(0, 40); // can split a multi-code-unit char in half |
| 33 | +``` |
| 34 | + |
| 35 | +Correct version: |
| 36 | + |
| 37 | +```js |
| 38 | +function truncate(text, n) { |
| 39 | + const seg = new Intl.Segmenter("en", { granularity: "grapheme" }); |
| 40 | + const out = []; |
| 41 | + for (const { segment } of seg.segment(text)) { |
| 42 | + if (out.length >= n) break; |
| 43 | + out.push(segment); |
| 44 | + } |
| 45 | + return out.join(""); |
| 46 | +} |
| 47 | + |
| 48 | +truncate("Hello 👨👩👧 family", 8); // "Hello 👨👩👧" — emoji intact |
| 49 | +``` |
| 50 | + |
| 51 | +Never splits a code-unit pair. Never breaks ZWJ-joined emoji. |
| 52 | + |
| 53 | +## Word segmentation (real word boundaries) |
| 54 | + |
| 55 | +`text.split(/\s+/)` works for English/French. It fails for: |
| 56 | + |
| 57 | +- **Japanese / Chinese / Thai** — no spaces between words |
| 58 | +- **Arabic** — words separated by spaces but compound forms tricky |
| 59 | +- **English contractions** — "don't" should be one or two words depending on use case |
| 60 | + |
| 61 | +```js |
| 62 | +const seg = new Intl.Segmenter("ja", { granularity: "word" }); |
| 63 | +[...seg.segment("今日は良い天気ですね")].filter(s => s.isWordLike).map(s => s.segment); |
| 64 | +// ["今日", "は", "良い", "天気", "です", "ね"] |
| 65 | +``` |
| 66 | + |
| 67 | +The browser uses the locale-specific dictionary. Japanese Mecab-style segmentation, Thai dictionary-based, English standard tokenization — all built in. |
| 68 | + |
| 69 | +## Line breaking |
| 70 | + |
| 71 | +For wrapping text yourself (canvas rendering, custom controls): |
| 72 | + |
| 73 | +```js |
| 74 | +const seg = new Intl.Segmenter("en", { granularity: "sentence" }); |
| 75 | +const sentences = [...seg.segment(longText)].map(s => s.segment); |
| 76 | +``` |
| 77 | + |
| 78 | +Granularity options: `grapheme | word | sentence`. |
| 79 | + |
| 80 | +Browsers natively use the same algorithm for `text-wrap: balance` and accessibility tools — so when you implement custom line breaking with `Intl.Segmenter`, you match what the browser does for native text. |
| 81 | + |
| 82 | +## Real example: emoji-safe character counter |
| 83 | + |
| 84 | +The "tweet still has 73 characters" UI: |
| 85 | + |
| 86 | +```js |
| 87 | +function characterCounter(text, max = 280) { |
| 88 | + const seg = new Intl.Segmenter("en", { granularity: "grapheme" }); |
| 89 | + const used = [...seg.segment(text)].length; |
| 90 | + return { used, remaining: max - used, valid: used <= max }; |
| 91 | +} |
| 92 | + |
| 93 | +characterCounter("Hello 👨👩👧!"); // { used: 8, remaining: 272, valid: true } |
| 94 | +``` |
| 95 | + |
| 96 | +Twitter/X's API counts the same way. Naive `.length` would say 14 and reject submissions that should pass. |
| 97 | + |
| 98 | +## Fuzzy search with locale-aware boundaries |
| 99 | + |
| 100 | +```js |
| 101 | +function findWord(text, query, locale = "en") { |
| 102 | + const seg = new Intl.Segmenter(locale, { granularity: "word" }); |
| 103 | + const words = [...seg.segment(text)] |
| 104 | + .filter(s => s.isWordLike) |
| 105 | + .map(s => s.segment.toLowerCase()); |
| 106 | + return words.includes(query.toLowerCase()); |
| 107 | +} |
| 108 | + |
| 109 | +findWord("the quick brown fox", "fox"); // true |
| 110 | +findWord("今日は良い天気ですね", "良い", "ja"); // true (segments correctly) |
| 111 | +``` |
| 112 | + |
| 113 | +Works across locales without per-language word-split logic. |
| 114 | + |
| 115 | +## Combine with String.prototype.normalize |
| 116 | + |
| 117 | +Some characters have multiple Unicode representations: |
| 118 | + |
| 119 | +```js |
| 120 | +"é" === "é"; // false sometimes (one is composed, one is decomposed) |
| 121 | + |
| 122 | +const a = "é".normalize("NFC"); |
| 123 | +const b = "é".normalize("NFC"); |
| 124 | +a === b; // true |
| 125 | + |
| 126 | +[...new Intl.Segmenter("en").segment(a)].length; // 1 |
| 127 | +``` |
| 128 | + |
| 129 | +Always normalize before segmenting if input might come from multiple sources (paste from email, OCR output, mixed inputs). |
| 130 | + |
| 131 | +## Performance note |
| 132 | + |
| 133 | +`Intl.Segmenter` is implemented in C++ in the browser — it's fast. The cost is the iterator allocation: |
| 134 | + |
| 135 | +```js |
| 136 | +// Slow if called per keystroke on a long text: |
| 137 | +[...new Intl.Segmenter("en", { granularity: "grapheme" }).segment(text)]; |
| 138 | + |
| 139 | +// Faster: reuse the segmenter |
| 140 | +const seg = new Intl.Segmenter("en", { granularity: "grapheme" }); |
| 141 | +function count(text) { return [...seg.segment(text)].length; } |
| 142 | +``` |
| 143 | + |
| 144 | +Cache the `Segmenter` instance globally; only the iteration is per-call. |
| 145 | + |
| 146 | +## Browser support |
| 147 | + |
| 148 | +- Chrome / Edge 87+ (December 2020) |
| 149 | +- Safari 14.1+ (April 2021) |
| 150 | +- Firefox 125+ (April 2024 — late but landed) |
| 151 | + |
| 152 | +Universal in 2025. For older Firefox, polyfill exists (`@formatjs/intl-segmenter`). |
| 153 | + |
| 154 | +## What this kills |
| 155 | + |
| 156 | +- `String.prototype.length` for "how many characters" — wrong by default for emoji and combined chars |
| 157 | +- `text.split("")` for grapheme iteration — wrong same way |
| 158 | +- Per-language word-splitting libraries — replaced by one locale-aware API |
| 159 | +- `.split(/\s+/)` for languages without spaces |
| 160 | + |
| 161 | +## What it doesn't do |
| 162 | + |
| 163 | +- **Character-by-character UTF-8 byte iteration** — that's `TextEncoder`, different concern |
| 164 | +- **Pinyin / romanization** — that's `Intl.NumberFormat` for digits, but text romanization needs a library |
| 165 | +- **Hyphenation** — separate spec (`hyphens: auto` in CSS, no JS API) |
| 166 | + |
| 167 | +## The headline |
| 168 | + |
| 169 | +Every "count characters" code path you've ever written is wrong by default for international text. `Intl.Segmenter` is the one-line fix — write it once, get correct behavior for English, Japanese, Hindi, Arabic, and emoji. The platform finally caught up to what users actually type. |
| 170 | + |
| 171 | +--- |
| 172 | + |
| 173 | +Practice JS basics in the [`js-variables`](/js-variables/0/) module on [Code Crispies](/) — covers strings + iteration patterns. |
0 commit comments