Insert a string at a specific index

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

    You can use Regular Expressions with a dynamic pattern.

    var text = "something";
    var output = "                    ";
    var pattern = new RegExp("^\\s{"+text.length+"}");
    var output.replace(pattern,text);
    

    outputs:

    "something      "
    

    This replaces text.length of whitespace characters at the beginning of the string output. The RegExp means ^\ - beginning of a line \s any white space character, repeated {n} times, in this case text.length. Use \\ to \ escape backslashes when building this kind of patterns out of strings.

提交回复
热议问题