Skip to content

Instantly share code, notes, and snippets.

@boo1ean
Created October 12, 2012 11:54
Show Gist options
  • Save boo1ean/3878870 to your computer and use it in GitHub Desktop.
Save boo1ean/3878870 to your computer and use it in GitHub Desktop.
Pluralize words javascript
// Original source http://lummie.co.uk/javascript-%E2%80%93-rails-like-pluralize-function/
var pluralize = (function() {
var Inflector = {
Inflections: {
plural: [
[/(quiz)$/i, "$1zes" ],
[/^(ox)$/i, "$1en" ],
[/([m|l])ouse$/i, "$1ice" ],
[/(matr|vert|ind)ix|ex$/i, "$1ices" ],
[/(x|ch|ss|sh)$/i, "$1es" ],
[/([^aeiouy]|qu)y$/i, "$1ies" ],
[/(hive)$/i, "$1s" ],
[/(?:([^f])fe|([lr])f)$/i, "$1$2ves"],
[/sis$/i, "ses" ],
[/([ti])um$/i, "$1a" ],
[/(buffal|tomat)o$/i, "$1oes" ],
[/(bu)s$/i, "$1ses" ],
[/(alias|status)$/i, "$1es" ],
[/(octop|vir)us$/i, "$1i" ],
[/(ax|test)is$/i, "$1es" ],
[/s$/i, "s" ],
[/$/, "s" ]
],
irregular: [
['move', 'moves' ],
['sex', 'sexes' ],
['child', 'children'],
['man', 'men' ],
['person', 'people' ]
],
uncountable: [
"sheep",
"fish",
"series",
"species",
"money",
"rice",
"information",
"equipment"
]
},
pluralize: function(word) {
for (var i = 0; i < Inflector.Inflections.uncountable.length; i++) {
var uncountable = Inflector.Inflections.uncountable[i];
if (word.toLowerCase() == uncountable) {
return uncountable;
}
}
for (var i = 0; i < Inflector.Inflections.irregular.length; i++) {
var singular = Inflector.Inflections.irregular[i][0];
var plural = Inflector.Inflections.irregular[i][1];
if ((word.toLowerCase() == singular) || (word == plural)) {
return plural;
}
}
for (var i = 0; i < Inflector.Inflections.plural.length; i++) {
var regex = Inflector.Inflections.plural[i][0];
var replace_string = Inflector.Inflections.plural[i][1];
if (regex.test(word)) {
return word.replace(regex, replace_string);
}
}
}
}
return function(word) {
return Inflector.pluralize(word);
}
})(),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment