0

I have tried various different string.insert(i, s) functions but none of them have worked with the loop that I have. Here is an example of my code:

var str = "  absolutely  pie";
var indices = [0, 12, 16]; // indices where I want to insert
var things = ["I", "love", 1]; // things I want to insert
for(var i = 0; i < indices.length; i++) {
    str = str.splice(indices[i], 0, things[i]);
}

This doesn't work. It's supposed to print out "I absolutely love pie1" , but instead it prints out:

"I absolutellove1y pie"

You can see the code here.

I have tried most of the examples from this question.

So what's the problem (is it how the insert methods are implemented?), and how can I fix this?

sinsedrix
  • 4,336
  • 4
  • 29
  • 53

3 Answers3

0

You need to account for the number of additional things that have been inserted in your string already by adding i to each index. Also note that you have one too many spaces at the beginning of your original string; it should be ' absolutely pie' instead of ' absolutely pie'.

Make sure that you convert your string to an array of characters (using String#split) before trying to call splice on it, because splice only works on arrays. You can then turn this array back into a string using Array#join.

var string = ' absolutely  pie'
var indices = [0, 12, 16]
var things = ['I', 'love', 1]

string = string.split('')

things.forEach(function (e, i) {
  string.splice(indices[i] + i, 0, e)
})

string = string.join('')

console.log(string) //=> 'I absolutely love pie1'
gyre
  • 16,369
  • 3
  • 37
  • 47
0

So your issue is that the indices you start with are relative to the original string. Inserting '1' at index 16 makes sense at first, but then you add 5 more characters so the actual index you want is 21. The easy fix here is to add an offset:

var str = "  absolutely  pie";
var indices = [0, 12, 16]; // indices where I want to insert
var things = ["I", "love", "1"]; // things I want to insert
var offset = 0;
for(var i = 0; i < indices.length; i++) {
  str = str.splice(indices[i] + offset, 0, things[i]);
  offset += things[i].length
}

The other issue is that if your target is "I absolutely love pie1", it some of the cases you're replacing the space in the original string an in others you're not. Testing my function with a 1 for the delCount param, I got I absolutely lovepie1. You need an extra "replacement space" between "absolutely" and "pie", or to remove it from the start and pass 0 as delCount instead.

xavdid
  • 5,092
  • 3
  • 20
  • 32
0

You're calculating the indexes based on the original string, but you need to take its modifications into account, it grows as the loop progresses.

Simply change the indices array to:

var indices = [0, 14, 22]; // indices where I want to insert
m1kael
  • 2,801
  • 1
  • 15
  • 14
  • this is fine, but requires calculating each new index by hand (by adding the length of the previous `thing`. Why not leave that to the code? – xavdid Mar 20 '17 at 03:27