I'm trying to add "-" before capital letters. e.g. helloWorld becomes hello-world.
My code, however, is placing the "-" in the array at the wrong places. i.e. thisIsSpinalTap becomes this-I-sSpin-alTap
What's wrong with my code?
function spinalCase(str){
str = str.replace(/ /g,'-');
strArr = str.split("");
for(i=1;i<str.length;i++){
if(str.charAt(i)==str.charAt(i).toUpperCase()&&str.charAt(i)!=="-"){
console.log(i);
strArr.splice(i,0,"-");
}
}
return strArr.join("");
}
spinalCase('thisIsSpinalTap'); // returns this-I-sSpin-alTap
str, but modifyingstrArrand once you've inserted one-character intostrArr, the two no longer match indexes properly so you insert in the wrong place. Remember, that.splice()will shift the indexes instrArr.