Insert a string at a specific index

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

    Just make the following function:

    function insert(str, index, value) {
        return str.substr(0, index) + value + str.substr(index);
    }
    

    and then use it like that:

    alert(insert("foo baz", 4, "bar "));
    

    Output: foo bar baz

    It behaves exactly, like the C# (Sharp) String.Insert(int startIndex, string value).

    NOTE: This insert function inserts the string value (third parameter) before the specified integer index (second parameter) in the string str (first parameter), and then returns the new string without changing str!

提交回复
热议问题