Insert a string at a specific index

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

    UPDATE 2016: Here is another just-for-fun (but more serious!) prototype function based on one-liner RegExp approach (with prepend support on undefined or negative index):

    /**
     * Insert `what` to string at position `index`.
     */
    String.prototype.insert = function(what, index) {
        return index > 0
            ? this.replace(new RegExp('.{' + index + '}'), '$&' + what)
            : what + this;
    };
    
    console.log( 'foo baz'.insert('bar ', 4) );  // "foo bar baz"
    console.log( 'foo baz'.insert('bar ')    );  // "bar foo baz"
    

    Previous (back to 2012) just-for-fun solution:

    var index = 4,
        what  = 'bar ';
    
    'foo baz'.replace(/./g, function(v, i) {
        return i === index - 1 ? v + what : v;
    });  // "foo bar baz"
    

提交回复
热议问题