简体   繁体   English

str.replace不替换$ 1

[英]str.replace does not replace the $1

I'm trying to make a little highlight function. 我正在尝试做一个突出显示功能。 The Problem i have is, that i does not insert the matched into the $1. 我的问题是,我没有将匹配项插入$ 1。 My function looks like 我的功能看起来像

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.

but i just get: 但是我得到:

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

so the $1 was not replaced by the matching. 因此$ 1没有被匹配项替换。

How can i solve that? 我该如何解决?

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替换$1 $&

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

See MDN replace reference : 请参阅MDN replace参考

$& Inserts the matched substring. $&插入匹配的子字符串。

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM