Created
June 30, 2017 13:20
-
-
Save Balder1840/61c1ccc76f9f607b8090377e8eea54f4 to your computer and use it in GitHub Desktop.
javascript to camel or pascal case
This file contains hidden or 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
function camelPad(str){ return str | |
// Look for long acronyms and filter out the last letter | |
.replace(/([A-Z]+)([A-Z][a-z])/g, ' $1 $2') | |
// Look for lower-case letters followed by upper-case letters | |
.replace(/([a-z\d])([A-Z])/g, '$1 $2') | |
// Look for lower-case letters followed by numbers | |
.replace(/([a-zA-Z])(\d)/g, '$1 $2') | |
.replace(/^./, function(str){ return str.toUpperCase(); }) | |
// Remove any white space left around the word | |
.trim(); | |
} | |
// remove \u00C0-\u00ff] if you do not want the extended letters like é | |
function toCamelCase(str) { | |
var retVal = ''; | |
retVal = $.trim(str) | |
.replace(/[^A-Za-z]/g, ' ') /* clean up non-letter characters */ | |
.replace(/(.)/g, function (a, l) { return l.toLowerCase(); }) | |
.replace(/(\s.)/g, function (a, l) { return l.toUpperCase(); }) | |
.replace(/[^A-Za-z\u00C0-\u00ff]/g, ''); | |
return retVal | |
} | |
function toPascalCase(str) { | |
var retVal = ''; | |
retVal = $.trim(str) | |
.replace(/[^A-Za-z]/g, ' ') /* clean up non-letter characters */ | |
.replace(/(.)/g, function (a, l) { return l.toLowerCase(); }) | |
.replace(/(^.|\s.)/g, function (a, l) { return l.toUpperCase(); }) | |
.replace(/[^A-Za-z\u00C0-\u00ff]/g, ''); | |
return retVal | |
} | |
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