Is there a splice method for strings?

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

    So, whatever adding splice method to a String prototype cant work transparent to spec...

    Let's do some one extend it:

    String.prototype.splice = function(...a){
        for(var r = '', p = 0, i = 1; i < a.length; i+=3)
            r+= this.slice(p, p=a[i-1]) + (a[i+1]||'') + this.slice(p+a[i], p=a[i+2]||this.length);
        return r;
    }
    
    • Every 3 args group "inserting" in splice style.
    • Special if there is more then one 3 args group, the end off each cut will be the start of next.
      • '0123456789'.splice(4,1,'fourth',8,1,'eighth'); //return '0123fourth567eighth9'
    • You can drop or zeroing the last arg in each group (that treated as "nothing to insert")
      • '0123456789'.splice(-4,2); //return '0123459'
    • You can drop all except 1st arg in last group (that treated as "cut all after 1st arg position")
      • '0123456789'.splice(0,2,null,3,1,null,5,2,'/',8); //return '24/7'
    • if You pass multiple, you MUST check the sort of the positions left-to-right order by youreself!
    • And if you dont want you MUST DO NOT use it like this:
      • '0123456789'.splice(4,-3,'what?'); //return "0123what?123456789"

提交回复
热议问题