Skip to content

Instantly share code, notes, and snippets.

@roylory
Last active October 12, 2015 01:07
Show Gist options
  • Save roylory/1f0555753d77db0cb475 to your computer and use it in GitHub Desktop.
Save roylory/1f0555753d77db0cb475 to your computer and use it in GitHub Desktop.
toSnakeCase() and toCamelCase() as String.prototype
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();
});
}
@roylory
Copy link
Author

roylory commented Oct 12, 2015

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