Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove part of string with javascript regex without repeating delimiting strings

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.

like image 371
Ellen Spertus Avatar asked Dec 15 '22 21:12

Ellen Spertus


2 Answers

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.

enter image description here

like image 156
anubhava Avatar answered Dec 17 '22 09:12

anubhava


Try below regex using grouping.

(?:<foo>)(.*?<\/foo>)

regex101 online demo

Pictorial representation: Debuggex Demo

enter image description here

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>
like image 30
Braj Avatar answered Dec 17 '22 11:12

Braj