Let’s say I have the following string:
Would you like some tea?
I want to replace only the second and third occurences of o
with 0
, so it becomes:
Would y0u like s0me tea?
Or maybe I would like to replace first and last occurence, like so:
W0ould you like s0me tea?
Any idea how I could achieve this?
Any help appreciated!
4
Answers
This is the best i could come up with
Using a regular expression and a callback function to replace:
If the found match is not at one of the given positions (starting to count at 0 here, as usual in programming), the
search
value will be returned as the "replacement" (so no change will actually happen), otherwise thereplace
value.(Constructing the RegExp might need additional escaping, if the search term contains characters that have special meaning in regular expressions – that goes a bit beyond the scope of this question, so please do some additional research on that on your own.)
By default, the
replace()
method replaces only the first occurrence of a match. But you can use regular expressions and theg
flag to replace all occurrences of a match:If you want the maximum speed use
String::indexOf()
to find matches andString::slice()
to slice unchanged parts into an array. Then join by the replacer: