Pluralization with the JavaScript Intl Library: A Comprehensive Guide

JavaScript
4 minutes read

Introduction

When building an application designed to reach users across the globe, it’s crucial to ensure your application speaks their language. Localization, adapting your application to different languages and regions, is a key component of user-friendly software. A cornerstone of localization is correctly handling pluralization, which, despite its seeming simplicity, can become complex very quickly when dealing with multiple languages.

Thankfully, JavaScript’s built-in internationalization library, Intl, offers a powerful toolset to help us out. In this article, we will explore Intl.PluralRules is a robust object for handling complex pluralization rules across various languages.

Basic Usage of Intl.PluralRules

Intl.PluralRules is an object in JavaScript’s Intl library. This object allows developers to properly format plurals based on different languages’ rules. Here’s how to use it at its most basic level.

Creating an Intl.PluralRules instance

Firstly, we instantiate an Intl.PluralRules object for a specific locale. In this case, we’re using en-US for U.S. English

let rules = new Intl.PluralRules('en-US');

Selecting the Correct Plural Form

Now, we want to select the correct form of a word based on a count. Let’s use the word apple. In English, one would say 1 apple but 2 apples.

Here’s how you can use Intl.PluralRules to select the correct form:

let numberOfApples = 1; // try changing this to different values
let form = rules.select(numberOfApples);

Here, rules.select(numberOfApples) will return a string that represents the plural form of the number. In English, this will be one for 1 and other for any other number.

Outputting the Correct Word Form

Now that we know the plural form, we can construct a string with the correct word form:

let output;

switch(form) {
    case 'one':
        output = `${numberOfApples} apple`;
        break;
    case 'other':
        output = `${numberOfApples} apples`;
        break;
}

console.log(output); // outputs: "1 apple"

Let’s put it all together:

let rules = new Intl.PluralRules('en-US');
let numberOfApples = 1; // try changing this to different values
let form = rules.select(numberOfApples);
let output;

switch(form) {
    case 'one':
        output = `${numberOfApples} apple`;
        break;
    case 'other':
        output = `${numberOfApples} apples`;
        break;
}

console.log(output); // outputs: "1 apple"

This code will correctly output 1 apple for numberOfApples = 1 and 2 apples, 3 apples, etc., for any other number.

By changing the locale and the rules in the switch statement, this code can be adapted to handle pluralization in any language that Intl.PluralRules supports. The exact forms and their rules vary from language to language, which is what makes Intl.PluralRules is such a powerful tool.

Pluralization in Different Languages

Not every language follows the English way of pluralization. Some languages like Russian have more complex rules, including different word forms for numbers classified as few, many, etc. The Intl library handles these beautifully. Let’s see an example:

let numberOfCats = 5;
let locale = 'ru-RU'; // Russian locale

let rules = new Intl.PluralRules(locale);
let form = rules.select(numberOfCats);

console.log(form); // outputs: "many"

Here, the Russian language has different plural categories, including ‘many’, which is used for numbers ending in 5 to 9 or 0, or numbers over 20 ending in 2-9.

Advanced Features of Intl.PluralRules

Intl.PluralRules also allows developers to use additional options to customize behavior:

Specifying options with Intl.PluralRules

When creating a new Intl.PluralRules object, we can pass in an options object as the second argument. This object allows us to specify how the pluralization should behave.

One key property we can set is type, which determines the kind of pluralization to be used. This can be set to cardinal (the default), which is used for quantities, or ordinal, which is used for ranks, positions, order, etc.

Here’s how you can use it:

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

console.log(pr.select(1)); // "one"
console.log(pr.select(2)); // "two"
console.log(pr.select(3)); // "few"
console.log(pr.select(4)); // "other"

In this example, we’re using ordinal pluralization, so ‘1’ returns ‘one’, ‘2’ returns ‘two’, ‘3’ returns ‘few’, and ‘4’ returns ‘other’. The actual strings returned will depend on the language specified.

Using Intl.PluralRules.resolvedOptions()

The resolvedOptions() method returns an object containing the options computed during the initialization of the Intl.PluralRules object. This can be useful to check the configuration of your Intl.PluralRules object:

let pr = new Intl.PluralRules('en-US', { type: 'ordinal' });
console.log(pr.resolvedOptions());

/** Outputs: 
{ 
 locale: "en-US", 
 type: "ordinal", 
 minimumIntegerDigits: 1, 
 minimumFractionDigits: 0, 
 maximumFractionDigits: 3, 
 pluralCategories: Array(4) ["one", "two", "few", "other"], 
 minimumSignificantDigits: 1, 
 maximumSignificantDigits: 21 
} */

Using Intl.PluralRules.supportedLocalesOf()

Intl.PluralRules.supportedLocalesOf() is a method that allows you to check if a locale is supported. This can be useful when you want to provide fallback behavior for unsupported locales. Here’s how you can use it:

let locales = ['en-US', 'fr-FR', 'es-ES', 'de-DE', 'zz-ZZ'];
let supportedLocales = Intl.PluralRules.supportedLocalesOf(locales);

console.log(supportedLocales);
// Outputs: Array(4) ["en-US", "fr-FR", "es-ES", "de-DE"]

In this example, we’re checking if the en-US, fr-FR, es-ES, de-DE, and zz-ZZ locales are supported. The zz-ZZ locale is made-up and is not supported, so it’s not included in the output.

These are just some of the advanced features Intl.PluralRules provides. Utilizing these features can greatly enhance the localization efforts of your application.

Handling Multiple Languages

If your application needs to support multiple languages, it’s crucial to correctly handle pluralization in all of these languages. Intl.PluralRules allows you to do this quite efficiently.

Method 1: Using Intl.PluralRules with multiple locales

The most straightforward way to use Intl.PluralRules with multiple languages is to create a new Intl.PluralRules instance for each language:

let englishRules = new Intl.PluralRules('en-US');
let russianRules = new Intl.PluralRules('ru-RU');
let arabicRules = new Intl.PluralRules('ar');

With these instances, you can correctly pluralize words in English, Russian, and Arabic.

Method 2: Creating a localization function

A more efficient approach might be to create a function that takes a locale and a number as arguments and returns the correct plural form:

function getPluralForm(locale, number) {
    let rules = new Intl.PluralRules(locale);
    return rules.select(number);
}

With this function, you can get the correct plural form for any number in any supported locale:

console.log(getPluralForm('en-US', 1)); // "one"
console.log(getPluralForm('ru-RU', 2)); // "few"
console.log(getPluralForm('ar', 0)); // "zero"

Handling multiple languages can be a complex task due to the varying rules for pluralization across languages. However, with Intl.PluralRules, this task becomes much more manageable. Whether you’re localizing your app for a few languages or providing support for a multitude of languages, Intl.PluralRules provides a robust solution.

Handling unsupported locales

Not all locales are supported by Intl.PluralRules. To provide a fallback behavior, you can use Intl.PluralRules.supportedLocalesOf():

function getPluralFormWithFallback(locale, number) {
    let supportedLocales = Intl.PluralRules.supportedLocalesOf([locale]);
    let resolvedLocale = supportedLocales[0] || 'en-US'; // fallback to 'en-US'
    let rules = new Intl.PluralRules(resolvedLocale);
    return rules.select(number);
}

With this function, if an unsupported locale is passed in, the function will default to using en-US.

Further Reading

Conclusion

In conclusion, understanding plural words in JavaScript, it might feel hard because languages are complex. But, with tools like Intl.PluralRules, you can do this well. This tool helps you make your website better for people around the world. It makes your website work well in many languages. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *