Due to the advancement of the matcher, there can be no overlapping matches. This means that the space after "in" cannot be used to match the space before "my."
Let's break it down with "|" indicating the position of the matcher:
'put image| in my gallery' //found the first space
'put image| in |my gallery' //completed a match
'put image |my gallery' //replaced the match with a " "
'put image |my gallery' //fails to match the required space before "my"
Solutions include running two operations (using .replace()
twice as shown in @alfasin's response) or utilizing the \b
anchor to match at word boundaries instead of spaces (as demonstrated in @Grim's suggestion).
Here is an alternative solution using a single replace operation (assuming a trailing space after the matched words):
'put image in my gallery'.replace(/\b(?:my|in) /g, '');
//'put image gallery'
The use of \b
, a zero-width assertion, ensures the matching occurs between word and non-word characters (\w
and \W
) to prevent overlaps and unnecessary spaces after replacements. Keep in mind, customized regular expressions may be needed for specific cases involving punctuation.