问题
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.
回答1:
You forgot about the brackets:
var pattern = new RegExp('(' + customVariable + ')','gi');
$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 $&
).
$&
Inserts the matched substring.
回答2:
You don't need to define a sub-pattern, since you're highlighting the entire match. You can simply do:
var pattern = new RegExp(customVariable, 'gi');
i.replace(pattern, '<span class="highlight">$&</span>');
$&
refers to the entire pattern.
来源:https://stackoverflow.com/questions/30767189/get-1-capture-group-with-dynamic-regexp