Hello!
Today, I'm going to show you how to pluralize any word in JavaScript (Node.js or Browser) in almost any language!
I've developed a very simple, but powerful package in JavaScript that will help you to achieve this goal. It's called Numerous.
I'm going to start with Node.js example.
First of all, let's start by installing the required dependency:
npm i -S numerous
Then, let's create a simple Node script:
const numerous = require('numerous');
// Returns "apple".
numerous.pluralize('en', 1, {
one: 'apple',
other: 'apples',
});
// Returns "cats".
numerous.pluralize('en', 2, {
one: 'cat',
other: 'cats',
});
numerous.pluralize(localeId, value, variants)
static function accepts three required arguments:
localeId
— a locale ID, e.g.en
for English,ru
for Russian, etc.value
— a value your pluralization should be based on, e.g.:1
,10
,100500
variants
— is an object that holds all possible pluralization forms of the word you want to pluralize
The complete list of all supported languages and locales could be found in Numerous locales document.
Key names for all possible variants could be found in the specific locale file. For example for English locale it could be found in English locale definition file.
e.g. for English the variant keys are:
one
— single form of the word, e.g. "child"other
— plural form of the word, e.g. "children"
In Node.js, the Numerous will load all the locales automatically when requested and cache them for later use. Locale definitions files are loaded only on demand (lazy-loaded) to preserve memory.
However, in Browser you will need to load each required locale manually before using it.
It's easy to use the static form of the API explained above, however, it's also possible to create an instance of the pluralizer in order to preconfigure it with some specific locale. It will allow you to reduce number of arguments you will require to pass when calling the pluralization function.
So, to create an instance of specific locale pluralizer call: numerous.create(localeId);
, e.g.
numerous.create('en');
.
Then you can use it's pluralize(value, variants)
method with only two arguments:
// Creating instances for specific locales
const englishPluralizer = numerous.create('en');
const russianPluralizer = numerous.create('ru');
// Returns "apple"
englishPluralizer.pluralize(1, {
one: 'apple',
other: 'apples',
});
// Returns "яблока"
russianPluralizer.pluralize(2, {
one: 'яблоко',
few: 'яблока',
many: 'яблок',
});
Please see the demo of how you could use this word pluralization library in browser environment with just vanilla JavaScript.
I hope this small article and the library itself will help you to make word pluralization easy in any JavaScript environment.
If you have any questions — please post them in the comments. I will be glad to help! Cheers!
numerous.pluralize(locale, calue, variants)
calue instead of value