ProllyGeek ProllyGeek - 3 months ago 14
Javascript Question

Is there a splice method for strings?

The Javascript

splice
only works with arrays. Is there similar method for strings? Or should I create my own custom function?

The
substr()
, and
substring()
methods will only return the extracted string and not modify the original string. What I want to do is remove some part from my string and apply the change to the original string. Moreover, the method
replace()
will not work in my case because I want to remove parts starting from an index and ending at some other index, exactly like what I can do with the
splice()
method. I tried converting my string to an array, but this is not a neat method.

Answer

It is faster to slice the string twice, like this:

function spliceSlice(str, index, count, add) {
  // We cannot pass negative indexes dirrectly to the 2nd slicing operation.
  if (index < 0) {
    index = str.length + index;
    if (index < 0) {
      index = 0;
    }
  }

  return str.slice(0, index) + (add || "") + str.slice(index + count);
}

than using a split followed by a join (Kumar Harsh's method), like this:

function spliceSplit(str, index, count, add) {
  var ar = str.split('');
  ar.splice(index, count, add);
  return ar.join('');
}

Here's a jsperf that compares the two and a couple other methods. (jsperf has been down for a few months now. Please suggest alternatives in comments.)

Although the code above implements functions that reproduce the general functionality of splice, optimizing the code for the case presented by the asker (that is, adding nothing to the modified string) does not change the relative performance of the various methods.