[SOLVED] I have a little question about regEx

I am currently working on the problem “Intermediate Algorithm Scripting: Spinal Tap Case”: Convert a string to spinal case. Spinal case is all-lowercase-words-joined-by-dashes.

I do have a bruteforce approach to the problem so I just match out all possible scenarios. However, there is a specific case where I think I have done it right but then I got it wrong, but when I modify it a bit it turned out to be working. I will specify:

The input string is “Teletubbies say Eh-oh”.
My regEx is /^[A-Z]*[a-z]+(?=[^a-z])|[A-Z][a-z]+(?=[^a-z]|$)|(?=[^A-Z])[a-z]+(?=[^a-z]|$)/g.

The confusing part is the last case (?=[^A-Z])[a-z]+(?=[^a-z]|$) (this is the one that works).

I wanted to match the words where it doesn’t start with an alphabetical character, and originally I used (?=[^A-Za-z])[a-z]+(?=[^a-z]|$). If I use this, I will miss out on “say” and “oh”.

I’m very confused as to why the one that seems more complete lookahead turns out not working, while the less complete one (that omits the lookahead for “no non-capitalized letter”) works.

Thank you for your hindsight. I’ll very much appreciate that!

P/S: I have played with it more and the latest version doesn’t even have the lookahead: [a-z]+(?=[^a-z]|$), and that works.

P/S2: I have another question after playing with it: Does match() work like splice? In other words, does it remove a word out of the string once it fits a criterion? Because that last regEx would definitely be wrong for a wide variety of cases if I only use it. But if I place it at last in my regEx, things are fine.

P/S3: I thought order in my regEx matters, but it seems it doesn’t. I put that confusing part at the beginning and it still works… I’m more confused now.

I think I have found the reason… I was supposed to be using lookbehind, not lookahead. I thought both are the same thing, while they aren’t. Because there’s no lookbehind in our curriculum, I had no idea.

Thank you if you’ve come around and I hope you’ll have a good day today. Cheers!