繁体   English   中英

str.replace不替换$ 1

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

我正在尝试做一个突出显示功能。 我的问题是,我没有将匹配项插入$ 1。 我的功能看起来像

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

如您所见,它应该包装匹配项。 但事实并非如此。 这是我如何使用它的示例:

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

我的预期结果是:

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

但是我得到:

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

因此$ 1没有被匹配项替换。

我该如何解决?

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

如果要用span包裹整个匹配项,请将$1替换$1 $&

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

请参阅MDN replace参考

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

with不是捕获组,您应该通过添加括号来对其进行转换:

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

输出将是:

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

暂无
暂无

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

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