Spinal Tap Case question

Tell us what’s happening:
I believe I have figured out this algorithm except for when there are no spaces or characters between the words. I figured I could use regex, but after I included it in the split+join series, I get errors in the Chrome dev console.

Your code so far


function spinalCase(str) {
 var reg = "([A-Z]+|[^A-Z]+)"
 var x = str.split(" ").join(",").split("_").join(",").split("-").join(",").split(reg).join(",")split(",");
 var stringNew=x.join("-").toLowerCase();
 return stringNew
 //console.log("x is "+ x);
 //console.log("stringNew is "+ stringNew);
  
}

spinalCase('This Is Spinal Tap');

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/spinal-tap-case/

I think you need to rethink the regex approach. First of all, your regex definition should look something like /\s/. That would match white space. You need to match for white space, underscores and dashes. You can join them with a |. You also need to split if the next char is an uppercase. This is a little trickier bu can also be done with regex. If I look at the documentation I see that there is the form of:

x(?=y)       Matches x only if x is followed by y. `

Now, of you leave out the x, it will match any char followed by y. Now, you have to figure out the regex for y to refer to uppercase chars, and put that in your regex, also separated by the or symbol, |. With that, you can do just one split with that regex, do a join and a toLowerCase. Really, with chained methods, this can be done in one line, inline with the return.

There are also looping solutions, but this is the sexiest.

Let us know if you need more help.

Is there any way to do this without regex? I don’t know too much of it.

Sure, you can do it without regex, but not nearly as easily. And if you are weak in regex, isn’t that a good reason to work at it?