Get $ 1 Capture Group with Dynamic RegExp
I was curious if anyone knows what I am doing wrong here. I want to use a variable inside an expression, but for some reason, when I try to do this, it doesn't seem to be grabbing the search query with $1
.
This returns correctly:
$('.content').html(function(_,i) {
return i.replace(/(cat)/gi, '<span class="highlight">$1</span>');
});
For some reason this is not the case:
$('.content').html(function(_,i) {
var customVariable = 'cat';
var pattern = new RegExp(customVariable,'gi');
return i.replace(pattern, '<span class="highlight">$1</span>');
});
I'm very new to capturing groups in RegExp and I couldn't find anyone else with this problem, so I'm guessing I'm missing something very basic.
source to share
You forgot about the parentheses:
var pattern = new RegExp('(' + customVariable + ')','gi');
$1
is a link back to group 1 and you don't have one.
In fact, you can find more about backlinks in JavaScript replace
on the MDN website. It's true that if you don't want to match the text before or after the alternatives, you just don't need to set up the capturing group, since when using a regex, all the matched text can be referenced by the pattern $&
(in your case, you just need to replace $1
with $&
).
$&
Inserts the matching substring.
source to share