Intl.PluralRules
The Intl.PluralRules object enables plural-sensitive formatting and plural language rules. It helps you determine which plural form (e.g., "one", "few", "many", "other") should be used for a given number in a specific locale.
1. Basic Usage
The constructor takes two optional arguments: locales and options. The select() method returns a string representing the plural category.
const pr = new Intl.PluralRules('en-US');
console.log(pr.select(0)); // "other" (0 items)
console.log(pr.select(1)); // "one" (1 item)
console.log(pr.select(2)); // "other" (2 items)
console.log(pr.select(100)); // "other" (100 items)
In English, most numbers are "other", except 1 which is "one".
2. Different Locales
Different languages have different pluralization rules.
// Arabic (ar-EG) has specific rules for 0, 1, 2, 3-10, 11-99, etc.
const ar = new Intl.PluralRules('ar-EG');
console.log(ar.select(0)); // "zero"
console.log(ar.select(1)); // "one"
console.log(ar.select(2)); // "two"
console.log(ar.select(6)); // "few"
console.log(ar.select(18)); // "many"
console.log(ar.select(100)); // "other"
3. Plural Categories
The standard categories returned by select() are:
zeroonetwofewmanyother
Not all languages use all categories. English only uses one and other.
4. Cardinal vs. Ordinal
The type option determines whether you are looking for cardinal numbers (1, 2, 3 - quantity) or ordinal numbers (1st, 2nd, 3rd - ranking).
cardinal: (Default) "1 item", "2 items".ordinal: "1st item", "2nd item".
const prOrdinal = new Intl.PluralRules('en-US', { type: 'ordinal' });
console.log(prOrdinal.select(1)); // "one" (st -> 1st)
console.log(prOrdinal.select(2)); // "two" (nd -> 2nd)
console.log(prOrdinal.select(3)); // "few" (rd -> 3rd)
console.log(prOrdinal.select(4)); // "other" (th -> 4th)
console.log(prOrdinal.select(21)); // "one" (st -> 21st)
5. Practical Example: Mapping to Strings
You can use the result of select() to pick the correct string from a map or object.
programming/javascript/vanilla/javascript programming/javascript/vanilla/intl-numberformat