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"
-
3Why do you need a regular expression for this? Just use the normal string replacement function.Barmar– Barmar2017-10-12 18:01:54 +00:00Commented Oct 12, 2017 at 18:01
Add a comment
|
2 Answers
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')