Skip to content

Instantly share code, notes, and snippets.

@tkharuk
Forked from kjantzer/Plural.js
Last active June 6, 2016 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkharuk/7c92d62393fea14c650cd955a11f9cb6 to your computer and use it in GitHub Desktop.
Save tkharuk/7c92d62393fea14c650cd955a11f9cb6 to your computer and use it in GitHub Desktop.
JavaScript: Plural - create a plural or singluar sentence based on a number
/**
* naive implementation of singular/plural sentence based on count.
* e.g.:
* var str = "Do you want to delete this? There {are|is} [num] book{s} attached."
*
* pluralize(str, 1); // => Do you want to delete this? There is 1 book attached."
* pluralize(str, 2); // => "Do you want to delete this? There are 2 books attached."
*
* @method function
*
* @param {String} str sentence with {} and []
* @param {Number} count
*
* @return {String}
*/
pluralize: function(str, count) {
var indx = count === 1 ? 1 : 0;
var result;
result = str.replace(/\[count\]/, count);
result = result.replace(/{(.[^}]*)}/g, function(wholematch, firstmatch) {
return firstmatch.split('|')[indx] || '';
});
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment