Skip to content

Instantly share code, notes, and snippets.

@chrisveness
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisveness/3bd4048e5184777c5df1 to your computer and use it in GitHub Desktop.
Save chrisveness/3bd4048e5184777c5df1 to your computer and use it in GitHub Desktop.
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