Insert a string at a specific index

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

    I know this is an old thread, however, here is a really effective approach.

    var tn = document.createTextNode("I am just  to help")
    t.insertData(10, "trying");
    

    What's great about this is that it coerces the node content. So if this node were already on the DOM, you wouldn't need to use any query selectors or update the innerText. The changes would reflect due to its binding.

    Were you to need a string, simply access the node's text content property.

    tn.textContent
    #=> "I am just trying to help"
    

提交回复
热议问题