Recipe 11.8
Applying Pluralization Rules
Intl.PluralRules
can tell you what form of a message string you should use based on the number passed to its select
method.
It returns a key such as one
or other
(differs depending on the locale) that you can use to look up different messages.
Code
JavaScript
function formatUserCount(users) {
// The variations of the message, depending
// on the count.
const messages = {
one: 'There is 1 user.',
other: `There are ${users.length} users.`
};
// Use Intl.PluralRules to determine which message
// should be displayed.
const rules = new Intl.PluralRules('en-US');
return messages[rules.select(users.length)];
}