I have string "foo?bar"
and I want to insert "baz"
at the ?
. This ?
may not always be at the 3 index, so I always want to insert something string at this ?
char to get "foo?bazbar"
Asked
Active
Viewed 105 times
-1

stackjlei
- 9,485
- 18
- 65
- 113
-
3Why do you need a regular expression for this? Just use the normal string replacement function. – Barmar Oct 12 '17 at 18:01
2 Answers
1
The String.protype.replace
method is perfect for this.
Example
let result = "foo?bar".replace(/\?/, '?baz');
alert(result);
I have used a RegEx in this example as requested, although you could do it without RegEx too.
Additional notes.
- If you expect the string
"foo?bar?boo"
to result in"foo?bazbar?boo"
the above code works as-is - If you expect the string
"foo?bar?boo"
to result in"foo?bazbar?bazboo"
you can change the call to.replace(/\?/g, '?baz')

Fenton
- 241,084
- 71
- 387
- 401
-1
You don't need a regular expression, since you're not matching a pattern, just ordinary string replacement.
string = 'foo?bar';
newString = string.replace('?', '?baz');
console.log(newString);

Barmar
- 741,623
- 53
- 500
- 612