Created
September 22, 2011 23:23
-
-
Save sentientmonkey/1236329 to your computer and use it in GitHub Desktop.
Pluralize for Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
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
Number.prototype.plural
could simply be written as:Also, I don't understand why you have to have 2 separate functions which
pluralize
is calling.they will never be called outside the scope of
pluralize
so it's much better to copy those 1-liners inside thepluralize
method IMHO.Also, why did you write
var str = this;
twice?