I was curious if anyone knows what I'm doing wrong here. I want to use a variable inside the expression but for some reason when I try to, it doesn't seem to grab the search term with the $1
.
This returns correctly:
$('.content').html(function(_,i) {
return i.replace(/(cat)/gi, '<span class="highlight">$1</span>');
});
For some reason, this does not:
$('.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 capture groups in RegExp and I couldn't find anyone else having this issue so I assume I'm missing something very simple.
You forgot about the brackets:
$1
is a backreference to group 1 and you do not have any.Actually, you can find more about backreferences in JavaScript
replace
on MDN Web site. It is true that in case you do not want to match any text before or after the alternatives, you just do not need to set up a capturing group, since when using a regex the whole matched text can be referenced with a$&
pattern (in your case, you just need to replace$1
with$&
).