Created
March 23, 2018 20:42
-
-
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.
This file contains 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
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