Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert between camel-cased & hyphenated strings (eg SomeResourceName <=> some-resource-name)
/**
* Returns camel-cased equivalent of (lower-case) hyphenated string.
*
* To enable round-tripping, hyphens not followed by a-z are left intact
* (can be checked for and/or removed manually if required).
*
* Only transforms ASCII capitals (lack of JavaScript Unicode regexp).
*/
function hyphenToCamel(str) {
// for Unicode transforms, replace [a-z] with \p{Ll} if available
return str
.toLowerCase()
.replace(/^[a-z]/g, function(letter) {
return letter.toUpperCase();
})
.replace(/\-[a-z]/g, function(letter) {
return letter.slice(1).toUpperCase();
});
}
/**
* Returns hyphenated equivalent of camel-cased string
*
* Only transforms ASCII capitals (lack of JavaScript Unicode regexp).
*/
function camelToHyphen(str) {
// for Unicode transforms, replace [A-Z] with \p{Lu} if available
return str
.replace(/^[A-Z]/g, function(letter) {
return letter.toLowerCase();
})
.replace(/[A-Z]/g, function(letter) {
return '-'+letter.toLowerCase();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.