Happy holiday folks! All the best from us at Digitpaint
🍬

Day 18

Plurization with Intl.PluralRules

Plural rules, you'd think that implementing them would be pretty simple, but since every language has its own rules around plurals, it can be quite tricky. The Intl Plural API helps you with this problem. It will tell you how to apply the pluralization rules according to the specified language.

In the demo, you can see what the pluralrules are for certain amounts of certain objects, in either Dutch, German or English. For now there is only Chrome 63+ support. Firefox 58 and Opera 50 will also support the API, but these are still in beta as of december 18th 2017.

Demo time!

Change the values below to see the plurals for the different languages and words.

1 Kerstboom

Pluralization

The Intl.PluralRules interface allows us to ask the browser how a certain amount of something should be pluralized in a certain language. The Intl.PluralRules interface itself does not contain any translations. All it tells is that for the English languages you should pluralize 0 for instance with the 'other' pluralization and 1 with 'one'.

Let's have a look at some code using the Intl.Pluralrules. When we call formatChristmasTree(1), it will provide us with the correct plural for 'one' christmas tree.

const languages = new Map([
  ['one',   'Christmas tree'],
  ['other', 'Christmas trees'],
]);

const pr = new Intl.PluralRules('en-US');

const formatChristmasTree = (n) => {
  const rule = pr.select(n);
  const language = languages.get(rule);
  return `${n} ${language}`;
};

formatChristmasTree(1);

In the code example above, we used a small dataset to demonstrate the workings of Intl.PluralRules. In real-world situations this data would be provided by a translation file.

In English, plurals are not that complex, with just two variants ('one' and 'other') but there are languages in which the rules are much more complex. In Irish, for example, there are specific rules for 'one', 'two', 'few', 'many' and 'other'. The API makes it much easier to deal with these kinds of languages.

Ordinal numbers

The API also can help us out with ordinal numbers (1st, 2nd, 3rd etc). It works in the same way as the other plurals do, but you have to change the value of type to ordinal. This is set to cardinal (which is what we used above) by default.

const pr = new Intl.PluralRules('en-US', {
  type: 'ordinal'
});

Browser compatibility

Browser support is limited to Chrome 63+ at the moment but in the coming months more browsers will implement the API.

  • 63+
  • 58+
  • 50+
  • android chrome

More about this

Demo source code

What to see how the demo is done?

  • JS
  • CSS (not much to see here, just a little bit of styling)
Back to home