Insert a string at a specific index

前端 未结 18 724
眼角桃花
眼角桃花 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:30

    Here is a method I wrote that behaves like all other programming languages:

    String.prototype.insert = function(index, string) {
      if (index > 0) {
        return this.substring(0, index) + string + this.substr(index);
      }
    
      return string + this;
    };
    
    //Example of use:
    var something = "How you?";
    something = something.insert(3, " are");
    console.log(something)

    Reference:

    • http://coderamblings.wordpress.com/2012/07/09/insert-a-string-at-a-specific-index/

提交回复
热议问题