0

I am trying to Us the javascript splice method to add a "-" before every capital latter in my array but it is not working. I don't know what I am doing wrong. Here is my code below.

function spinalCase(str) {
  let strArr = [];
  for(let i = 0; i < str.length; i++){
    strArr.push(str[i]);
  }
  for(let i = 0; i < strArr.length; i++){
    if(strArr[i] !== strArr[i].toLowerCase()){
      strArr.splice(strArr.indexOf(strArr[i]),0, "-");
    }
  } 
console.log(strArr);
}

spinalCase('thisIsSpinalTap');

3 Answers 3

1

When you add a new element with splice you're increasing the length of the array and the loop is never able to finish. If you work the loop from the end of the array to the beginning instead you can avoid this problem.

function spinalCase(str) {
  let strArr = [];
  for (let i = 0; i < str.length; i++) {
    strArr.push(str[i]);
  }

  // Work the loop from the end to the beginning
  for (let i = strArr.length - 1; i >= 0 ; i--) {
    if (strArr[i] !== strArr[i].toLowerCase()) {
      strArr.splice(strArr.indexOf(strArr[i]), 0, "-");
    }
  }
  console.log(strArr.join(''));
}

spinalCase('thisIsSpinalTap');

Sign up to request clarification or add additional context in comments.

Comments

1

I know you wanted to use splice, but here is a little regex solution; just in case.

function spinalCase(str) {
 return str.replace(/[A-Z]/g, "-$&").toLowerCase();
}

console.log(spinalCase("thisIsSpinalTap"))
// this-is-spinal-tap

Comments

0

You changed your array when you do:

strArr.splice(strArr.indexOf(strArr[i]),0, "-");

So strArr.length is not constant for the loop for(let i = 0; i < strArr.length; i++)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.