Last active
October 12, 2015 01:07
-
-
Save roylory/1f0555753d77db0cb475 to your computer and use it in GitHub Desktop.
toSnakeCase() and toCamelCase() as String.prototype
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
var hasSpace = /\s/; | |
var hasSeparator = /[\W_]/; | |
var separatorSplitter = /[\W_]+(.|$)/g; | |
var camelSplitter = /(.)([A-Z]+)/g; | |
function unseparate(string) { | |
return string.replace(separatorSplitter, function (m, next) { | |
return next ? ' ' + next : ''; | |
}); | |
} | |
function uncamelize(string) { | |
return string.replace(camelSplitter, function (m, previous, uppers) { | |
return previous + ' ' + uppers.toLowerCase().split('').join(' '); | |
}); | |
} | |
String.prototype.toNoCase = function () { // https://github.com/ianstormtaylor/to-no-case | |
if (hasSpace.test(this)) return this.toLowerCase(); | |
if (hasSeparator.test(this)) return (unseparate(this) || this).toLowerCase(); | |
return uncamelize(this).toLowerCase(); | |
} | |
String.prototype.toSpaceCase = function () { // https://github.com/ianstormtaylor/to-space-case | |
return this.toNoCase().replace(/[\W_]+(.|$)/g, function (matches, match) { | |
return match ? ' ' + match : ''; | |
}); | |
} | |
String.prototype.toSnakeCase = function () { // https://github.com/ianstormtaylor/to-snake-case | |
return this.toSpaceCase().replace(/\s/g, '-'); | |
} | |
String.prototype.toCamelCase = function () { // https://github.com/ianstormtaylor/to-camel-case | |
return this.toSpaceCase().replace(/\s(\w)/g, function (matches, letter) { | |
return letter.toUpperCase(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As angular filters: https://gist.github.com/roylory/ad50488e35c51402b88e#file-angular_string_normalization_filters-js