Many developers might want to concentrate in coding important logic but there are also the need to pluralize English words or strings to present the correct meaning.
What is Pluralize English String
As simple as as it sounds, it is to display the plural form of a word or text when the amount is more than 1.
The most easiest plural form we know is appending an s to the word. But some not all words are that simple. Let’s take a look at the examples below.
// Singular form -> Plural form // apple -> apples // foot -> feet // person -> people // tooth -> teeth
Thus, we as developers will really prefer simply solutions out there.
Dictionary definition here.
How to Pluralize English String
One of the manual way we can do is to check for the number before display the text we want.
In the below example, we are using string interpolation. Based on a if-else logic, we display person or people.
let number = 1;
console.log(`${number} ${number > 1 ? 'people' : 'person'}`);
// 1 man
number = 5;
console.log(`${number} ${number > 1 ? 'people' : 'person'}`);
// 5 menHowever, this method will become time consuming as we need to write test to cover all range of values and will become inefficient. Hence, an easier solution available to use is Pluralize plugin. Pluralize is also available in npm.
Using it is very simple. If we already have the counter, just plug it in and it will display in the correct form.
let pluralize = require('pluralize')
console.log(pluralize('person' , 0));
// people
console.log(pluralize('person' , 0, true));
// 0 people
console.log(pluralize('person' , 1, true));
// 1 person
console.log(pluralize('person' , 5, true));
// 5 peopleIf we want to change the plural form for a certain word, it can also be easily done.
let pluralize = require('pluralize')
console.log(pluralize('person' , 5, true));
// 5 people
pluralize.addIrregularRule('person', 'person');
console.log(pluralize('person' , 5, true));
// 5 personConclusion
If you are are considering to reduce your workload, this plugin is definitely a must try. It is lightweight and will also help to reduce your codes.


No Responses Yet