简体   繁体   中英

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. 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.

How can i solve that?

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

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

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

See MDN replace reference :

$& Inserts the matched substring.

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

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

Output will be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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