Skip to content

Instantly share code, notes, and snippets.

@nickihastings
Created March 23, 2018 20:42
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 nickihastings/ff2e7bc4a6d8e90c7c1cd76a02a7bb92 to your computer and use it in GitHub Desktop.
Save nickihastings/ff2e7bc4a6d8e90c7c1cd76a02a7bb92 to your computer and use it in GitHub Desktop.
Convert a string to spinal case. Spinal case is all-lowercase-words-joined-by-dashes.
function spinalCase(str) {
// "It's such a fine line between stupid, and clever."
// --David St. Hubbins
function processStr(match, offset, string){
//if the offset is not the first letter and there isn't already a hyphen,
//add a hyphen then change the letter to lowercase
if(offset !== 0 && string[offset-1] !== '-'){
return '-' + match.toLowerCase();
}
return match.toLowerCase();
}
//first check for spaces, then check for underscores, then check for capitals
var newStr = str.replace(/\s/g, '-').replace(/_/g, '-').replace(/[A-Z]/g, processStr);
return newStr;
}
spinalCase('This Is Spinal Tap');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment