Insert a string at a specific index

前端 未结 18 866
眼角桃花
眼角桃花 2020-11-22 14:02

How can I insert a string at a specific index of another string?

 var txt1 = \"foo baz\"

Suppose I want to insert \"bar \" after the \"foo

18条回答
  •  自闭症患者
    2020-11-22 14:44

    Using slice

    You can use slice(0,index) + str + slice(index). Or you can create a method for it.

    String.prototype.insertAt = function(index,str){
      return this.slice(0,index) + str + this.slice(index)
    }
    console.log("foo bar".insertAt(4,'baz ')) //foo baz bar

    Splice method for Strings

    You can split() the main string and add then use normal splice()

    String.prototype.splice = function(index,del,...newStrs){
      let str = this.split('');
      str.splice(index,del,newStrs.join('') || '');
      return str.join('');
    }
    
    
     var txt1 = "foo baz"
    
    //inserting single string.
    console.log(txt1.splice(4,0,"bar ")); //foo bar baz
    
    
    //inserting multiple strings
    console.log(txt1.splice(4,0,"bar ","bar2 ")); //foo bar bar2 baz
    
    
    //removing letters
    console.log(txt1.splice(1,2)) //f baz
    
    
    //remving and inseting atm
    console.log(txt1.splice(1,2," bar")) //f bar baz

    Applying splice() at multiple indexes

    The method takes an array of arrays each element of array representing a single splice().

    String.prototype.splice = function(index,del,...newStrs){
      let str = this.split('');
      str.splice(index,del,newStrs.join('') || '');
      return str.join('');
    }
    
    
    String.prototype.mulSplice = function(arr){
      str = this
      let dif = 0;
      
      arr.forEach(x => {
        x[2] === x[2] || [];
        x[1] === x[1] || 0;
        str = str.splice(x[0] + dif,x[1],...x[2]);
        dif += x[2].join('').length - x[1];
      })
      return str;
    }
    
    let txt = "foo bar baz"
    
    //Replacing the 'foo' and 'bar' with 'something1' ,'another'
    console.log(txt.splice(0,3,'something'))
    console.log(txt.mulSplice(
    [
    [0,3,["something1"]],
    [4,3,["another"]]
    ]
    
    ))

提交回复
热议问题