Insert a string at a specific index

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

    This is basically doing what @Base33 is doing except I'm also giving the option of using a negative index to count from the end. Kind of like the substr method allows.

    // use a negative index to insert relative to the end of the string.
    
    String.prototype.insert = function (index, string) {
      var ind = index < 0 ? this.length + index  :  index;
      return  this.substring(0, ind) + string + this.substr(ind);
    };
    

    Example: Let's say you have full size images using a naming convention but can't update the data to also provide thumbnail urls.

    var url = '/images/myimage.jpg';
    var thumb = url.insert(-4, '_thm');
    
    //    result:  '/images/myimage_thm.jpg'
    

提交回复
热议问题