Is there a better way to solve the Spinal Tap Case by possibly combining each step into fewer lines? I’m sure changing the value of the str variable 3 times probably isn’t best practice.
function spinalCase(str) {
str = str.replace(/([a-z])([A-Z])/g, '$1 $2'); // add space between lowercase to uppercase
str = str.replace(/\W|_/g,'-');// change non letters to -
str = str.toLowerCase(str.replace(/\W|_/g,'-'));// make it all lowercase
return str;
}
You don’t need the str.replace(/\W|_/g,'-') here.
As far as chaining it all into a single line - six of one/half dozen of the other. I personally prefer not to.
My original solution didn’t have the repeated regex on line 4 after the toLowerCase, I think I was trying to figure out how to string them together on my own and forgot to delete it before copying into the forum question.
I like the one liner solutions with stringing them all together. That’s what I was looking for but wasn’t sure how exactly you could do it with multiple replace calls. Thanks for the help everyone!
@ArielLeslie, you said you prefer doing it on multiple lines, would you do it like I originally did by changing the value of the str variable each time? Or is there another way to do it on multiple lines?
I reviewed positive and negative lookahead to pass this challenge and here is my workaround:
function spinalCase(str) {
// "It's such a fine line between stupid, and clever."
// --David St. Hubbins
// first, I split the string to make it an array of substrings \W = [A-Za-z-0-9],(?=[A-Z])=positive lookahaed .
str=str=str.split(/\W|_|(?=[A-Z])/g).join("-").toLowerCase();
return str;
}
spinalCase('This Is Spinal Tap');