-
-
Save jerriclynsjohn/b4d0a9ad3794dc3008be144d1cc2919c to your computer and use it in GitHub Desktop.
An convenience method for converting to and from different casing types.
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
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