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!
Using a regular expression and a callback function to replace:
function replaceOccurences(text, search, replace, positions) {
let regex = new RegExp(search, 'g')
let counter = 0;
return text.replace(regex, function(match) {
return positions.includes(counter++) ? replace : search;
})
}
console.log(
replaceOccurences('foo bar baz foo djd foo sjsh', 'foo', 'XYZ', [1, 2])
);
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 the replace
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.)