JavaScript Intl for Text: Sorting with Collator, Plural Rules, Segmenter, Display Names and Locales
The text side of Intl: sorting and searching strings with Intl.Collator and localeCompare (accents, case, numbers), choosing plural forms and ordinal suffixes with PluralRules, splitting text into graphemes, words and sentences with Segmenter, plus DisplayNames, Intl.Locale and locale negotiation.
kvi5hnuCode Sprout team member5 min readOn this page
Article 85 formatted numbers and dates. Text has its own locale-sensitive problems: alphabetical order differs between languages, "1 item / 2 items" has more than two forms in many languages, and what users see as one character can be several code points. This article covers the Intl tools for text.
Sorting strings: Intl.Collator
The default sort() compares UTF-16 code units, which is wrong for people:
const names = ["Émile", "zoe", "Zack", "adam", "Ölaf"];
console.log([...names].sort());
console.log([...names].sort(new Intl.Collator("en").compare));
console.log([...names].sort(new Intl.Collator("sv").compare));
[ 'Zack', 'adam', 'zoe', 'Émile', 'Ölaf' ]
[ 'adam', 'Émile', 'Ölaf', 'Zack', 'zoe' ]
[ 'adam', 'Émile', 'Zack', 'zoe', 'Ölaf' ]
- Code-unit order puts all uppercase letters before lowercase, and accented letters after
z. Intl.Collator("en")sorts the way an English reader expects.- In Swedish,
Öis a separate letter that comes afterZ. Correct order really is language-specific.
str.localeCompare(other, locales, options) does the same comparison for one pair, but for sorting arrays a Collator is much faster, because it's set up once.
Collator options
const files = ["file10.txt", "file9.txt", "File1.txt"];
console.log([...files].sort(new Intl.Collator("en", { numeric: true }).compare));
const base = new Intl.Collator("en", { sensitivity: "base" });
console.log(base.compare("resume", "Résumé"), base.compare("a", "b"));
const caseFirst = new Intl.Collator("en", { caseFirst: "upper" });
console.log(["b", "a", "B", "A"].sort(caseFirst.compare));
[ 'File1.txt', 'file9.txt', 'file10.txt' ]
0 -1
[ 'A', 'a', 'B', 'b' ]
numeric: truecompares digit runs as numbers ("natural sort"), sofile9comes beforefile10. This is what file explorers do.sensitivitydecides which differences count:"base"ignores accents and case (a = á = A),"accent"ignores case only,"case"ignores accents only, and"variant"(default for sorting) counts everything.caseFirstchooses whether uppercase or lowercase sorts first when letters are otherwise equal.usage: "search"tunes the collator for matching rather than ordering.
Accent- and case-insensitive search
A sensitivity: "base" collator is a simple way to compare user input "loosely":
const loose = new Intl.Collator("en", { usage: "search", sensitivity: "base" });
const cities = ["São Paulo", "Zürich", "Montréal", "Kraków"];
const query = "zurich";
console.log(cities.filter((city) => loose.compare(city, query) === 0));
[ 'Zürich' ]
For substring search ("contains"), normalize both sides instead: remove accents with normalize("NFD") and \p{M} (article 82), and lowercase them.
Plural rules: Intl.PluralRules
"You have 1 message" vs "You have 2 messages" looks like a simple n === 1 check, but it isn't in general. English has two forms; Arabic has six; Russian and Polish have different forms for 2 to 4 and 5 and up; Japanese has one. Intl.PluralRules tells you which category a number falls into, and you supply the text for each category:
const en = new Intl.PluralRules("en-US");
console.log([0, 1, 2].map((n) => en.select(n)));
console.log(new Intl.PluralRules("ru").select(3), new Intl.PluralRules("ru").select(5));
console.log(new Intl.PluralRules("ar").select(2), new Intl.PluralRules("ja").select(1));
const messages = { one: "You have # new message", other: "You have # new messages" };
const say = (n) => messages[en.select(n)].replace("#", n);
console.log(say(1), "|", say(4));
[ 'other', 'one', 'other' ]
few many
two other
You have 1 new message | You have 4 new messages
The categories are zero, one, two, few, many and other. Translation tools (ICU MessageFormat, i18next and similar) use exactly these categories, so translators can provide each form.
Ordinals: 1st, 2nd, 3rd
With type: "ordinal", PluralRules picks ordinal categories:
const ordinal = new Intl.PluralRules("en", { type: "ordinal" });
const suffix = { one: "st", two: "nd", few: "rd", other: "th" };
const nth = (n) => n + suffix[ordinal.select(n)];
console.log([1, 2, 3, 4, 11, 12, 13, 21, 22, 101, 111].map(nth).join(" "));
1st 2nd 3rd 4th 11th 12th 13th 21st 22nd 101st 111th
The tricky cases (11th, 12th, 13th but 21st, 22nd) are handled by the rules, not by your code.
Splitting text: Intl.Segmenter
Intl.Segmenter splits text into graphemes (user-perceived characters), words or sentences, following Unicode's rules for the given locale.
Graphemes

const family = "\u{1F468}\u200D\u{1F469}\u200D\u{1F467}"; // man, ZWJ, woman, ZWJ, girl
const graphemes = new Intl.Segmenter("en", { granularity: "grapheme" });
console.log(family.length, [...family].length, [...graphemes.segment(family)].length);
const text = "H\u00e9llo \u{1F44B}\u{1F3FD}!"; // é, then a waving hand with a skin-tone modifier
const chars = Array.from(graphemes.segment(text), (s) => s.segment);
console.log(text.length, chars.length, chars.slice(0, 7).join("|"));
console.log(chars.reverse().join(""));
8 5 1
11 8 H|é|l|l|o| |👋🏽
!👋🏽 olléH
lengthcounts UTF-16 code units, and spreading counts code points (article 14). Neither matches what users see for emoji with modifiers, flags, joined emoji, or letters with combining accents.- Grapheme segmentation is the right way to count characters for a limit ("140 characters"), truncate without cutting an emoji in half, or reverse a string.
Words and sentences
const words = new Intl.Segmenter("en", { granularity: "word" });
const english = "Hello, world! It's 2026.";
console.log([...words.segment(english)].filter((s) => s.isWordLike).map((s) => s.segment));
const japanese = new Intl.Segmenter("ja", { granularity: "word" });
console.log([...japanese.segment("今日は良い天気です")].filter((s) => s.isWordLike).map((s) => s.segment));
const sentences = new Intl.Segmenter("en", { granularity: "sentence" });
console.log([...sentences.segment("Hi there. How are you? Fine!")].map((s) => s.segment.trim()));
[ 'Hello', 'world', "It's", '2026' ]
[ '今日', 'は', '良い', '天気', 'です' ]
[ 'Hi there.', 'How are you?', 'Fine!' ]
text.split(" ") can't split Japanese, Chinese or Thai, which don't use spaces between words. The word segmenter can, using dictionaries built into the engine. Each segment also has index (its position) and isWordLike (to skip punctuation and spaces), which makes word counts, "jump to next word" behavior and search highlighting straightforward.
Names of languages, regions and currencies: Intl.DisplayNames
const regions = new Intl.DisplayNames(["en"], { type: "region" });
console.log(regions.of("IN"), regions.of("JP"), regions.of("BR"));
console.log(new Intl.DisplayNames(["de"], { type: "language" }).of("fr"));
console.log(new Intl.DisplayNames(["en"], { type: "currency" }).of("EUR"));
console.log(new Intl.DisplayNames(["ja"], { type: "region" }).of("US"));
India Japan Brazil
Französisch
Euro
アメリカ合衆国
Perfect for language pickers and country dropdowns, without shipping translation tables. Types include language, region, script, currency, calendar and dateTimeField.
Intl.Locale and choosing a locale
Intl.Locale parses and inspects locale tags:
const loc = new Intl.Locale("en-Latn-US", { hourCycle: "h23" });
console.log(loc.language, loc.script, loc.region, loc.baseName, loc.hourCycle);
console.log(String(new Intl.Locale("pt").maximize()));
console.log(Intl.getCanonicalLocales("EN-us"), Intl.NumberFormat.supportedLocalesOf(["en-US", "xx-YY"]));
en Latn US en-Latn-US h23
pt-Latn-BR
[ 'en-US' ] [ 'en-US' ]
maximize()fills in the most likely script and region (Portuguese defaults to Brazil);minimize()does the opposite.supportedLocalesOftells you which of the requested locales the engine supports.- When you pass an array of locales, Intl uses the first one it supports, falling back to the runtime's default. Passing
navigator.languages(in browsers) gives users their full preference list.
Intl.supportedValuesOf("currency") (also "timeZone", "unit", "calendar", "numberingSystem", "collation") lists everything the engine supports, which is handy for building option lists.
Common questions
Why is my sorted list wrong for names with accents or capitals?
sort() without a comparator compares UTF-16 code units. Use array.sort(new Intl.Collator(locale).compare), or localeCompare for single comparisons.
How do I sort strings that contain numbers, like "v2" and "v10"?
Use a collator with numeric: true: the code below.
new Intl.Collator(undefined, { numeric: true }).compare
How do I limit input to 20 characters without breaking emoji?
Count graphemes with Intl.Segmenter (granularity "grapheme") and cut at a segment boundary: the code below. Note that maxlength on HTML inputs counts UTF-16 code units.
Array.from(seg.segment(text), (s) => s.segment).slice(0, 20).join("")
Is n === 1 ? "item" : "items" good enough?
For English UI only, mostly. For any other language, use Intl.PluralRules with per-category messages, because many languages have more forms or different rules (French, for example, treats 0 as singular).
Summary
Intl.Collator(andlocaleCompare) sorts and compares strings by language rules; options includenumeric,sensitivity,caseFirstandusage. Reuse one collator for sorting.Intl.PluralRulesmaps numbers to plural categories (one,few,many,other...), and to ordinal categories withtype: "ordinal".Intl.Segmentersplits text into graphemes (what users see as characters), words (even in languages without spaces) and sentences.Intl.DisplayNamesgives localized names of languages, regions, scripts and currencies.Intl.Localeparses locale tags;supportedLocalesOfandsupportedValuesOfreport what's available.
Practice Questions
Sort ["item20", "Item3", "item100"] naturally and case-insensitively.
Answer
list.sort(new Intl.Collator("en", { numeric: true, sensitivity: "base" }).compare)
Gives [ 'Item3', 'item20', 'item100' ].
What do "🇮🇳".length, [..."🇮🇳"].length and the grapheme count return?
Answer
4, 2 and 1. A flag is two "regional indicator" code points, each a surrogate pair, shown as one character.
Write pluralize(n) that returns "1 file" or "N files" using Intl.PluralRules.
Answer
const pr = new Intl.PluralRules("en");
const pluralize = (n) => `${n} ${pr.select(n) === "one" ? "file" : "files"}`;
How would you count the words in a Chinese paragraph?
Answer
[...new Intl.Segmenter("zh", { granularity: "word" }).segment(text)].filter((s) => s.isWordLike).length
Splitting on spaces doesn't work because Chinese doesn't separate words with spaces.
Previous: JavaScript Intl: Formatting Numbers, Currencies, Dates, Relative Times and Durations for Any Locale
Next: The JavaScript console API: log Levels, Formatting, table, group, time, count, assert and trace

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.