JavaScript pluralize an english string

In PHP, I use Kuwamoto's class to pluralize nouns in my strings. I didn't find something as good as this script in javascript except for some plugins. So, it would be great to have a javascript function based on Kuwamoto's class.

http://kuwamoto.org/2007/12/17/improved-pluralizing-in-php-actionscript-and-ror/


Solution 1:

Simple version (ES6):

const maybePluralize = (count, noun, suffix = 's') =>
  `${count} ${noun}${count !== 1 ? suffix : ''}`;

Usage:

maybePluralize(0, 'turtle'); // 0 turtles
maybePluralize(1, 'turtle'); // 1 turtle
maybePluralize(2, 'turtle'); // 2 turtles
maybePluralize(3, 'fox', 'es'); // 3 foxes

This obviously doesn't support all english edge-cases, but it's suitable for most purposes

Solution 2:

Use Pluralize

There's a great little library called Pluralize that's packaged in npm and bower.

This is what it looks like to use:

import Pluralize from 'pluralize';

Pluralize( 'Towel', 42 );       // "Towels"

Pluralize( 'Towel', 42, true ); // "42 Towels"

And you can get it here:

https://github.com/blakeembrey/pluralize