Skip to content

Instantly share code, notes, and snippets.

@trenskow
Last active July 18, 2022 11:02
Show Gist options
  • Save trenskow/a0d1e2cf67f93437f98fbc20559a0619 to your computer and use it in GitHub Desktop.
Save trenskow/a0d1e2cf67f93437f98fbc20559a0619 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]);
}
}
});
}
@trenskow
Copy link
Author

'theStruggleIsReal'.toCase('kebab').toCase('pascal').toCase('snake').toCase('domain').toCase('camel')

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