How to remove part of a string using javascript regex without repeating string strings

I would like to remove unknown substring when it occurs between two known substring ( <foo>and </foo>). For example, I would like to convert:

hello <foo>remove me</foo>

at

hello <foo></foo>

I can do it with

s = ...
s.replace(/<foo>.*?<\/foo>/, '<foo></foo>')

but I would like to know whether there is a way to do this without repeating known substring ( <foo>and </foo>) in the regular expression and replacement text.

+4
source share
2 answers

You can grab the tag in captured groupand use it later as a backlink:

var repl = s.replace(/<(foo)>.*?<\/\1>/, '<$1></$1>');
//=> hello <foo></foo>

\1 $1 # 1.

enter image description here

+10

.

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

- regex101

: Debuggex

enter image description here

:

var re = /(?:<foo>)(.*?<\/foo>)/;
var str = 'hello <foo>remove me</foo>';
var subst = '<foo></foo>';

var result = str.replace(re, subst);

:

hello <foo></foo>
+2

Source: https://habr.com/ru/post/1548138/


All Articles