Multiple instances of a character?

Trying to get all instances of a blank space using indexOf and a for loop and add it to arrofSpacIndex array

function allInstancesOfBlankSpace (words) 
{
  var j=0;
 
  var arrOfSpaceIndex = [];
  //creating an array to store all instances of blank spaces
  for(i=0;  j = -1; i = pos)
 
  {
    var pos = words.indexOf('', i )
   //gets integer of next instance of character want it to be separate from j so position of i doesnt get set to -1
  
   var j= words.indexOf('', i )
   //checks if there is another instance of the blank space if none then -1 which should stop loop from iterating
   
   
    arrOfSpaceIndex.push(pos)
    //adds position of blank space to array
  }

 return arrOfSpaceIndex
}



allInstancesOfBlankSpace("HELLO MY FRIEND")

So you are wanting to return an array storing the indexes containing space characters in a given string? For example, allInstancesOfBlankSpace (“I am a string.”) should return [1, 4, 6]?

If so, do you have to use indexOf and a for loop or is it ok with just a for loop?

indexOf is not really needed:

function allInstancesOfBlankSpace(words) {
	let arrOfSpaceIndex = [];
	//creating an array to store all instances of blank spaces
	for (let i = 0; i < words.length; i++) {
		if (words[i] === ' ') {
			arrOfSpaceIndex.push(i);
		}
	}
	return arrOfSpaceIndex;
}
1 Like