Skip to content

Instantly share code, notes, and snippets.

@jerriclynsjohn
Forked from trenskow/toCase.js
Created October 14, 2019 01:01
Show Gist options
  • Save jerriclynsjohn/b4d0a9ad3794dc3008be144d1cc2919c to your computer and use it in GitHub Desktop.
Save jerriclynsjohn/b4d0a9ad3794dc3008be144d1cc2919c to your computer and use it in GitHub Desktop.
An convenience method for converting to and from different casing types.
if (!String.prototype.toCase) {
Object.defineProperties(String.prototype, {
'toCase': {
value: function(type = 'camel') {
const seperators = {
'camel': '',
'pascal': '',
'snake': '_',
'domain': '.',
'kebab': '-'
};
if (Object.keys(seperators).indexOf(type) == -1) {
throw new TypeError('Type must either be `camel`, `pascal`, `snake`, `domain` or `kebab`');
}
let parts = this.split(/(?=[A-Z])|_|-| |\./)
.map((key, idx) => {
switch (type) {
case 'camel':
if (idx == 0) return key.toLowerCase();
// falls through
case 'pascal':
return key.charAt(0).toUpperCase() + key.substring(1).toLowerCase();
case 'domain':
// falls through
case 'kebab':
// falls through
case 'snake':
return key.toLowerCase();
}
});
return parts.join(seperators[type]);
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment