Created
January 25, 2010 17:44
-
-
Save ktopping/286058 to your computer and use it in GitHub Desktop.
A javascript function for turning a space (or punctuation) - delimited string into a camel case String.
This file contains 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
// There's probably a more concise solution, but I prefer clarity over conciseness | |
// Splits on any number of non-word characters. | |
// Apostrophes don't cause case-change. | |
function toCamelCase(str) { | |
if (str==null || str==undefined || str.length==0) return str; | |
str = str.replace(/'/g, ""); | |
var arr = str.split(/[^\w]+/g); // split on any sequence of one or more | |
// non-word chars. | |
var ret = ""; | |
// Look for the first non-zero-length String. | |
for (var i=0;i<arr.length;i++) { | |
if (arr[i].length>0) { | |
ret += arr[i++]; | |
break; | |
} | |
} | |
// Concatenate all subsequent non-zero-length String, after uppercasing | |
// the first letter. | |
for (;i<arr.length;i++) { | |
if (arr[i].length>0) { | |
ret += arr[i].substr(0, 1).toUpperCase(); | |
} | |
if (arr[i].length>1) { | |
ret += arr[i].substr(1); | |
} | |
} | |
return ret; | |
} | |
toCamelCase(" a better place hooray!") == "aBetterPlaceHooray"; | |
toCamelCase("Here's A string to turn into Camel-case") == "HeresAStringToTurnIntoCamelCase"; | |
toCamelCase("In Denmark, for instance") == "InDenmarkForInstance"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
8 year old gem.