I solved the Spinal Tap Case challenge, but something has been bothering me since I looked at the suggested solutions.
For some reason, I was stuck thinking I had to split the string into an array of individual words and I couldn’t realize that I could just insert a non-word character before every uppercase letter and then replace.
Once I saw the regex I could see it, but the fact I couldn’t come up with that on the spot makes me feel kinda stupid.
How can one go about finding better solutions, instead of tunnel visioning in the first one that comes to mind? Is it just a matter of experience?
my solution:
edit: just realized the first part of the regex was useless
function spinalCase(str) {
//remove white spaces and dashes to clean up the string and turn into array
let words = str.split(/[^A-Za-z]+/)
//basically match any words
let regex = /[A-Z][a-z]+|[a-z]+/g
//get all words starting with an uppercase letter and split them into their own array item (in case there are two or more words together)
for (let i = 0; i<words.length; i++){
if(words[i].match(regex) !== null){
let temp = words[i].match(regex)
words.splice(i, 1, ...temp)
}
}
return words.join("-").toLowerCase()
}
spinalCase('Teletubbies say Eh-oh');
Challenge: Spinal Tap Case
Link to the challenge: