insert space after and before in string at specific index multiple times javascript p5.js

1k Views Asked by At
str = '12512';
indexes = [0, 3]
lngth = 2; 

result should be: str = ' 12 5 12 '

How do I add spaces there, knowing the character length, and index at which they are located?

I tried to do it with

for (i=0; i<indexes.length; i++){
     var spb = [str.slice(0, indexes[i]), " ", str.slice(indexes[i])].join('');
     var spa = [str.slice(0, indexes[i]+lngth), " ", str.slice(indexes[i]+lngth)].join('');
       console.log(spb);
       console.log(spa);
    }

It seems to work, though the output is like this, cause i needed to search for each index:

spa 12 512
spb  12512
spa 12512 
spb 125 12

How to make output like this ' 12 5 12 '

1

There are 1 best solutions below

4
On BEST ANSWER

You need to iterate backwards

for (i = indexes.length - 1; i >= 0; i--) {
   str = str.slice(0, indexes[i] + lngth) + " " + str.slice(indexes[i] + lngth);
   str = str.slice(0, indexes[i]) + " " + str.slice(indexes[i]);
}

Why?

Otherwise the indices gets mixed up, for example after inserting one space all following indices are shifted by one. Iterating backwards avoids this.