Insert multiple elements into array with splice method

I have a problem I’m trying to solve. I am trying to insert a space where ever there is a instance of a capital letter. The problem is that the space is pushed into the correct index but for all other instances where a capital letter appears, it doesn’t apply that space. I have researched extensively about the splice methods but could not figure out a solution to my problem. Can someone point me in the right direction.

function solution(string) {
  
  let splitStr = [...string];
  
  
  for(let i = 0; i < splitStr.length; i++) {
    
    if(!splitStr[i].toUpperCase()) return
    
    if(splitStr[i] === splitStr[i].toUpperCase()) {
        let indexOfCapLetter = splitStr.indexOf(splitStr[i].toUpperCase());
        splitStr.splice(indexOfCapLetter, 0, ' ' );
        
        return splitStr
      }
    
  }
  
 
}

Answer

First issue is that you’re returning the array inside your if statement within the loop. This escapes the function after the first capital letter. But after that there’s another issue.

Whenever you add a new element to the array, the characters after it are moved to a higher index.

To counter this you can loop through the array backwards so the affected elements are always ones you’ve already parsed:

function solution(string) {
  
  let splitStr = [...string];
  
  
  for(let i = splitStr.length-1; i >=0; i--) {
    
    if(splitStr[i] === splitStr[i].toUpperCase()) {
        splitStr.splice(i, 0, ' ' );
      }
  }
  
  return splitStr.join('');
}

console.log(solution('HelloWorldLongString'))