Challenge: Intermediate Algorithm Scripting - Spinal Tap Case
I hate reGex with all my heart, but here is what I came up with. Do you detect any flaws in here? Can it be optimized? Any recommendations for me based on this code? It passes the test but I spent like 3 hours to do this.
Your code so far
function spinalCase(str) {
let p = str
.replace(/\s|_/g,' ')
.replace(/-/g,' ')
.split(/([A-Z][a-z]+|-)/g)
.join(' ')
var x = p.trim().replace(/\s+/g,'-').toLowerCase()
return x
}
console.log(spinalCase("AllThe-small Things"))
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Safari/605.1.15
Challenge: Intermediate Algorithm Scripting - Spinal Tap Case
Hey, it passes the tests, so there are no flaws as far as that goes. You could combine the first two replaces. You don’t need p and x, you could write this as one return statement. And if you wanted to brush up on lookaheads you could simplify this quite a bit (you wouldn’t need any replaces). But you are still learning, so don’t knock yourself too much over not having the “perfect” solution.
Now that you have solved it you could look at the solutions in the hints. Solution 3 uses a lookahead and is the most concise. I would study that one for sure to make sure you understand how it works.
Thanks a lot for your review! Just check the 3rd solution. That was incredible. My mistake was that I didn’t look through all of the RegEx methods in my notes. Somehow I missed the positive lookaheads and they were the changing point. I was stuck for many hours trying to split the string with no dividers like “HelloThere” and that’s where the lookaheads are helpful.
Guess I need to prepare for the RegEx tasks better because there are a lot of expression methods which are essential to optimize your code.
Regex and “optimize” don’t usually go together. Regex is a very powerful tool, but its also somewhat slow. Its good to know about Regex, but don’t forget about other options available to you.