I have something like:
Some MY_WORD stupid txt='other text MY_WORD' and another MY_WORD stupid text and txt='something else MY_WORD' and also txt='here nothing to replace' and here txt='again to replace MY_WORD here'
I want to replace MY_WORD
with OTHER_WORD
but only if it is inside txt='
and '
/(?<=txt='.*)MY_WORD(?=.*')/g
Some MY_WORD stupid txt='other text OTHER_WORD' and another MY_WORD stupid text and txt='something else OTHER_WORD' and also txt='here nothing to replace' and hexe txt='again to replace OTHER_WORD here'
But look behind is not supported in all browsers, so it is not good approach.
A tried with this but even it says there are groups of matches, I $3 is empty.
(txt=')((.*)(MY_WORD))?
2
Answers
You can match the text between
txt='
and'
using a simpletxt='[^']*'
regex. Then, upon finding the matches, replace all occurrences ofMY_WORD
with what you need inside an arrow function:where
x
stands for the whole match.See the JavaScript demo:
I would just search for
txt = '...MY_WORD
and replace it with the helpof a capturing group before
MY_WORD
. Also, handle optional spaces aroundthe equal sign and be sure that
MY_WORD
is a full word and not part ofa word (such as
DUMMY_WORD
) by also matching word boundaries withb
.The regex pattern:
I use
[^']*
instead of.*
.Full JS working example where you can change the input to test it: