Created
December 26, 2013 02:47
-
-
Save marshallswain/8129143 to your computer and use it in GitHub Desktop.
camelCase a string. Originally found here: http://valschuman.blogspot.com/2012/08/javascript-camelcase-function.html?view=flipcard Thank you, Val Schuman;
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
Wrote a function to CamelCase a string in JavaScript. Because, AFAIK, CamelCasing applies only to programming, the function makes sure the string conforms to a legal variable name standard, removing all illegal characters, as well as making sure the string starts with a letter (not a number or an underscore.) | |
You can add the function to the String object prototype: | |
String.prototype.toCamelCase = function() { | |
// remove all characters that should not be in a variable name | |
// as well underscores an numbers from the beginning of the string | |
var s = this.replace(/([^a-zA-Z0-9_\- ])|^[_0-9]+/g, "").trim().toLowerCase(); | |
// uppercase letters preceeded by a hyphen or a space | |
s = s.replace(/([ -]+)([a-zA-Z0-9])/g, function(a,b,c) { | |
return c.toUpperCase(); | |
}); | |
// uppercase letters following numbers | |
s = s.replace(/([0-9]+)([a-zA-Z])/g, function(a,b,c) { | |
return b + c.toUpperCase(); | |
}); | |
return s; | |
} | |
Or use it as a stand-alone function: | |
function toCamelCase(s) { | |
// remove all characters that should not be in a variable name | |
// as well underscores an numbers from the beginning of the string | |
s = s.replace(/([^a-zA-Z0-9_\- ])|^[_0-9]+/g, "").trim().toLowerCase(); | |
// uppercase letters preceeded by a hyphen or a space | |
s = s.replace(/([ -]+)([a-zA-Z0-9])/g, function(a,b,c) { | |
return c.toUpperCase(); | |
}); | |
// uppercase letters following numbers | |
s = s.replace(/([0-9]+)([a-zA-Z])/g, function(a,b,c) { | |
return b + c.toUpperCase(); | |
}); | |
return s; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment