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
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.