Skip to content

Instantly share code, notes, and snippets.

@miketierney
Created October 19, 2011 21:07
Show Gist options
  • Save miketierney/1299678 to your computer and use it in GitHub Desktop.
Save miketierney/1299678 to your computer and use it in GitHub Desktop.
Some nice javascript string manipulations
/**
* Takes a string and capitalizes the first letter.
*
* @example
* "this is an all lower-case string".capitalize();
* // => "This is an all lower-case string"
*
* @return String
**/
String.prototype.capitalize = function(){
return this.charAt(0).toUpperCase() + this.slice(1);
};
/**
* Splits on non-word characters, then joins the pieces back together.
*
* NOTE: this won't do any sort of capitalization, in order to avoid some
* weirdness (at least, unpredictable weirdness).
*
* @example
* "Multiple/Categorical/Choices".classify();
* // => "MultipleCategoricalChoices"
*
* "Mike's Bar & Grill".classify();
* // => MikesBarGrill"
*
* "Won't capitalize Words".classify();
* // => "WontcapitalizeWords" -- if we capitalized words, it'd look like this: "WonTCapitalizeWords"
*
* @return String
**/
String.prototype.classify = function(){
return this.split(/\W/).join("");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment