Insert a string at a specific index

前端 未结 18 871
眼角桃花
眼角桃花 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 14:32

    You can do it easily with regexp in one line of code

    const str = 'Hello RegExp!';
    const index = 6;
    const insert = 'Lovely ';
        
    //'Hello RegExp!'.replace(/^(.{6})(.)/, `$1Lovely $2`);
    const res = str.replace(new RegExp(`^(.{${index}})(.)`), `$1${insert}$2`);
        
    console.log(res);

    "Hello Lovely RegExp!"

提交回复
热议问题