Skip to content

Instantly share code, notes, and snippets.

@ktopping
Created January 25, 2010 17:44
Show Gist options
  • Save ktopping/286058 to your computer and use it in GitHub Desktop.
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.
// 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";
@grosscorporation
Copy link

8 year old gem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment