Skip to content

Instantly share code, notes, and snippets.

@philipszdavido
Created October 9, 2017 16:12
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 philipszdavido/dcaef159e69e6fc27ae86d67b67949ba to your computer and use it in GitHub Desktop.
Save philipszdavido/dcaef159e69e6fc27ae86d67b67949ba to your computer and use it in GitHub Desktop.
String.prototype.plural = function () {
if (this.lastChar() === 'y') {
if ( (this.charAt(this.length - 2)).isVowel() ) {
// If the y has a vowel before it (i.e. toys), then you just add the s.
return this + 's';
}
else {
// If a this ends in y with a consonant before it (fly), you drop the y and add -ies to make it plural.
return this.slice(0, -1) + 'ies';
}
}
else if (this.substring( this.length - 2) === 'us') {
// ends in us -> i, needs to preceed the generic 's' rule
return this.slice(0, -2) + 'i';
}
else if (['ch', 'sh'].indexOf(this.substring( this.length - 2)) !== -1 || ['x','s'].indexOf(this.lastChar()) !== -1) {
// If a this ends in ch, sh, x, s, you add -es to make it plural.
return this + 'es';
}
else {
// anything else, just add s
return this + 's';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment