Is there a splice method for strings?

前端 未结 10 2354
你的背包
你的背包 2020-11-30 23:32

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

The substr(),

相关标签:
10条回答
  • 2020-12-01 00:04

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

    function spliceSlice(str, index, count, add) {
      // We cannot pass negative indexes directly 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.

    0 讨论(0)
  • 2020-12-01 00:07

    Here's a nice little Curry which lends better readability (IMHO):

    The second function's signature is identical to the Array.prototype.splice method.

    function mutate(s) {
        return function splice() {
            var a = s.split('');
            Array.prototype.splice.apply(a, arguments);
            return a.join('');
        };
    }
    
    mutate('101')(1, 1, '1');
    

    I know there's already an accepted answer, but hope this is useful.

    0 讨论(0)
  • 2020-12-01 00:08

    Simply use substr for string

    ex.

    var str = "Hello world!";
    var res = str.substr(1, str.length);
    

    Result = ello world!

    0 讨论(0)
  • 2020-12-01 00:09

    The method Louis's answer, as a String prototype function:

    String.prototype.splice = function(index, count, add) {
      if (index < 0) {
        index = this.length + index;
        if (index < 0) {
          index = 0;
        }
      }
      return this.slice(0, index) + (add || "") + this.slice(index + count);
    }
    

    Example:

     > "Held!".splice(3,0,"lo Worl")
     < "Hello World!"
    
    0 讨论(0)
提交回复
热议问题