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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've re-written your code in the way I believe is better:
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!