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 60 times
-1
stackjlei
- 8,765
- 16
- 51
- 106
-
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
- 224,347
- 65
- 373
- 385
-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
- 669,327
- 51
- 454
- 560