[英]What does \\$& in “str.replace(specials, ”\\$&“)” mean?
[英]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.