Pluralize Counts With Intl.PluralRules
Choose singular or plural forms by CLDR plural category, including custom two and few forms for non-English locales.
Code
export function pluralize(count, singular, plural, locale = "en") {
if (typeof count !== "number" || !Number.isFinite(count)) {
throw new TypeError("count must be a finite number");
}
const rules = new Intl.PluralRules(locale);
const category = rules.select(count);
const forms = typeof plural === "string"
? { one: singular, other: plural }
: { one: singular, other: singular, ...plural };
const word = forms[category] ?? forms.other ?? singular;
return String(count) + " " + word;
}
export function pluralizeWithNumber(count, singular, plural, locale = "en") {
const formatted = new Intl.NumberFormat(locale).format(count);
const text = pluralize(count, singular, plural, locale);
const separator = text.indexOf(" ");
return separator === -1 ? text : formatted + text.slice(separator);
}Inside the snippet
Pluralize Counts With Intl.PluralRules keeps everything in the functions pluralize and pluralizeWithNumber.
Invalid states are rejected up front: it throws TypeError instead of continuing with bad data.
Using it
The main signature reads export function pluralize(count, singular, plural, locale = "en")
Treat pluralize as the API: import it, and ignore the supporting code.
Key statements
return separator === -1 ? text : formatted + text.slice(separator);
const formatted = new Intl.NumberFormat(locale).format(count);
const word = forms[category] ?? forms.other ?? singular;
Interactive Tools for This Topic
Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.JSON Formatter & ValidatorFormat, beautify, and validate JSON data with configurable indentation. Instantly catches syntax errors and displays a pretty-printed tree structure.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.
FAQ
- How are precondition violations signaled?
- `TypeError` is raised at the guard, so invalid state never reaches the main logic.
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. The file defines `pluralize`, `pluralizeWithNumber` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.