Is there a splice method for strings?

前端 未结 10 2346
你的背包
你的背包 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-11-30 23:45

    Louis's spliceSlice method fails when add value is 0 or other falsy values, here is a fix:

    function spliceSlice(str, index, count, add) {
      if (index < 0) {
        index = str.length + index;
        if (index < 0) {
          index = 0;
        }
      }
      const hasAdd = typeof add !== 'undefined';
      return str.slice(0, index) + (hasAdd ? add : '') + str.slice(index + count);
    }
    

提交回复
热议问题