I would like to remove an unknown substring when it occurs between two known substrings (<foo>
and </foo>
). For example, I'd like to convert:
hello <foo>remove me</foo>
to:
hello <foo></foo>
I can do it with:
s = ...
s.replace(/<foo>.*?<\/foo>/, '<foo></foo>')
but I'd like to know if there's a way to do it without repeating the known substrings (<foo>
and </foo>
) in the regex and the replacement text.
You can capture tag in a captured group
and use it later as back reference:
var repl = s.replace(/<(foo)>.*?<\/\1>/, '<$1></$1>');
//=> hello <foo></foo>
Note \1
and $1
are back references to the captured group #1.
Try below regex using grouping.
(?:<foo>)(.*?<\/foo>)
regex101 online demo
Pictorial representation: Debuggex Demo
Sample code:
var re = /(?:<foo>)(.*?<\/foo>)/;
var str = 'hello <foo>remove me</foo>';
var subst = '<foo></foo>';
var result = str.replace(re, subst);
Output:
hello <foo></foo>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With