Is there a splice method for strings?

前端 未结 10 2385
你的背包
你的背包 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:59

    Edit

    This is of course not the best way to "splice" a string, I had given this as an example of how the implementation would be, which is flawed and very evident from a split(), splice() and join(). For a far better implementation, see Louis's method.


    No, there is no such thing as a String.splice, but you can try this:

    newStr = str.split(''); // or newStr = [...str];
    newStr.splice(2,5);
    newStr = newStr.join('');
    

    I realise there is no splice function as in Arrays, so you have to convert the string into an array. Hard luck...

提交回复
热议问题