Question about Spinal Tap Case

Question about Spinal Tap Case
0

#1

My question is why second for loop in my solution doesn’t work? Here is my code:
function spinalCase(str) {
str = str.replace(/_/g, “”).replace(/ /g, “-”).replace(str.charAt(0), str[0].toLowerCase());

for (var i = 0; i < str.length; i++) {
if(/[A-Z]/.test(str[i]) === true && str.charAt(i) === str[i].toUpperCase()) {
str = str.replace(str.charAt(i), ("-" + str[i].toLowerCase()));
}
}
for (i = 0; i < str.length; i++) {
var re = “/-/”;
if(str[i] === “-” && str[i + 1] === “-”) {
str = str.replace(re, “”);
}
}
// “It’s such a fine line between stupid, and clever.”
// --David St. Hubbins
return str;
}

spinalCase(“This Is Spinal Tap”);


#2

Oh, there is lot going on :wink:

The main reason is you shouldn’t include regular expressions in quotes.

Also you actually don’t need second for loop if you use g flag in the regular expression.


#3

Thanks! I will do a RegEx tutorial :wink: