Is there a splice method for strings?

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

    I would like to offer a simpler alternative to both the Kumar/Cody and the Louis methods. On all the tests I ran, it performs as fast as the Louis method (see fiddle tests for benchmarks).

    String.prototype.splice = function(startIndex,length,insertString){
        return this.substring(0,startIndex) + insertString + this.substring(startIndex + length);
    };
    

    You can use it like this:

    var creditCardNumber = "5500000000000004";
    var cardSuffix = creditCardNumber.splice(0,12,'****');
    console.log(cardSuffix);  // output: ****0004
    

    See Test Results: https://jsfiddle.net/0quz9q9m/5/

提交回复
热议问题