Insert a string at a specific index

前端 未结 18 874
眼角桃花
眼角桃花 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
    2020-11-22 14:26

    Given your current example you could achieve the result by either

    var txt2 = txt1.split(' ').join(' bar ')
    

    or

    var txt2 = txt1.replace(' ', ' bar ');
    

    but given that you can make such assumptions, you might as well skip directly to Gullen's example.

    In a situation where you really can't make any assumptions other than character index-based, then I really would go for a substring solution.

提交回复
热议问题