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 '
You need to iterate backwards
Why?
Otherwise the indices gets mixed up, for example after inserting one space all following indices are shifted by one. Iterating backwards avoids this.