68
An convenience method for converting to and from different casing types. · GitHu...
source link: https://gist.github.com/trenskow/a0d1e2cf67f93437f98fbc20559a0619
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
An convenience method for converting to and from different casing types. · GitHub
Instantly share code, notes, and snippets.
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]); | |
} | |
} | |
}); | |
} |
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK