Skip to content

Instantly share code, notes, and snippets.

@sentientmonkey
Created September 22, 2011 23:23
Show Gist options
  • Save sentientmonkey/1236329 to your computer and use it in GitHub Desktop.
Save sentientmonkey/1236329 to your computer and use it in GitHub Desktop.
Pluralize for Javascript
Number.prototype.plural = function(){
if(this > 1 || this == 0){
return true;
} else {
return false;
}
}
String.prototype.pluralize_rules = function(){
return [[new RegExp('$', 'gi'), 's']];
}
String.prototype.pluralize = function(number){
var str = this;
if(number.plural()){
var str = this;
var rules = this.pluralize_rules();
for(var r=0; r < rules.length; r++){
if(str.match(rules[r][0])){
str = str.replace(rules[r][0], rules[r][1]);
}
}
}
return str.toString();
}
@yairEO
Copy link

yairEO commented Mar 29, 2017

I've re-written your code in the way I believe is better:

String.prototype.pluralize = function(count){
  var str = this,
      rules = [[new RegExp('$', 'gi'), 's']], r;

  if( count > 1 || !count ){
    for( r=0; r < rules.length; r++ )
      if( str.match(rules[r][0]) )
        str = str.replace(rules[r][0], rules[r][1]);
  }

  return str.toString();
}

I don't know regex, could you maybe explain what your regex does and why do you need it instead of adding s to the end of the string?
Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment