Last active
July 18, 2022 11:02
-
-
Save trenskow/a0d1e2cf67f93437f98fbc20559a0619 to your computer and use it in GitHub Desktop.
An convenience method for converting to and from different casing types.
This file contains 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
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
'theStruggleIsReal'.toCase('kebab').toCase('pascal').toCase('snake').toCase('domain').toCase('camel')