str.replace不替换$1

时间:2021-05-16 16:50:19

I'm trying to make a little highlight function. The Problem i have is, that i does not insert the matched into the $1. My function looks like

我想做一个高亮显示的功能。我的问题是,我没有将匹配项插入到$1中。我的函数的样子

getMatch(str, search) {
    let result = str.replace(new RegExp(search, 'gi'), '<span class="match">$1</span>');
    return result;
}

as you can see, it should wrap the match. but it does not. here an example how i use it:

正如你所看到的,它应该结束比赛。但事实并非如此。这里有一个我如何使用它的例子:

let string = 'My string with higlighting.';
let match = getMatch(string, 'With');

my expected result is:

我预期的结果是:

My string <span class="match">with</span> highlighting.

我的字符串 与高亮显示。 类="match">

but i just get:

但我只是得到:

My string <span class="match">$1</span> highlighting.

我的字符串 $1高亮显示。 类="match">

so the $1 was not replaced by the matching.

所以1美元没有被匹配的取代。

How can i solve that?

我怎么解决呢?

2 个解决方案

#1


2  

Your 'With' has no capturing groups, thus, $1 is parsed as a literal string.

您的“With”没有捕获组,因此,$1被解析为文字字符串。

If you want to wrap the whole match with span, replace $1 with $&.

如果您想用span来包装整个匹配项,请将$1替换为$&。

getMatch(str, search) {
    let result = str.replace(new RegExp(search, 'gi'), '<span class="match">$&</span>');
    return result;
}

See MDN replace reference:

看到MDN取代参考:

$& Inserts the matched substring.

$&插入匹配的子字符串。

#2


1  

The with is not a capturing group, you should transform it by adding parenthesis :

with不是一个捕获组,你应该通过添加括号来改变它:

let string = 'My string with higlighting.';
let match = getMatch(string, '(With)');

Output will be:

输出将:

My string <span class="match">with</span> higlighting.

#1


2  

Your 'With' has no capturing groups, thus, $1 is parsed as a literal string.

您的“With”没有捕获组,因此,$1被解析为文字字符串。

If you want to wrap the whole match with span, replace $1 with $&.

如果您想用span来包装整个匹配项,请将$1替换为$&。

getMatch(str, search) {
    let result = str.replace(new RegExp(search, 'gi'), '<span class="match">$&</span>');
    return result;
}

See MDN replace reference:

看到MDN取代参考:

$& Inserts the matched substring.

$&插入匹配的子字符串。

#2


1  

The with is not a capturing group, you should transform it by adding parenthesis :

with不是一个捕获组,你应该通过添加括号来改变它:

let string = 'My string with higlighting.';
let match = getMatch(string, '(With)');

Output will be:

输出将:

My string <span class="match">with</span> higlighting.