I current have the following code:
const pattern = "quick";
const re = new RegExp(pattern, "gi");
const string = "The quick brown fox jumped over the lazy QUICK dog";
const replaced = string.replace(pattern, "<b>" + pattern + "</b>");
console.log(replaced);
It produces the following:
The <b>quick</b> brown fox jumped over the lazy QUICK dog
What I want is:
The <b>quick</b> brown fox jumped over the lazy <b>QUICK</b> dog
I'm having two issues.
Firstly, why isn't QUICK
being replaced when I'm using a case insensitive regex?
Secondly, how do I ensure that QUICK
is replaced with <b>QUICK</b>
and not <b>quick</b>
?
You need to pass <b>$&</b>
as the second parameter to .replace
to insert the matched substring:
const string = "The quick brown fox jumped over the lazy QUICK dog";
console.log(
string.replace(/quick/gi, '<b>$&</b>')
);
Your QUICK
isn't being replaced in your original code because
const replaced = string.replace(pattern,
is passing pattern, which is a string, rather than your constructed regex (whose variable name is re
). If you had passed re
, you would see:
const pattern = "quick";
const re = new RegExp(pattern, "gi");
const string = "The quick brown fox jumped over the lazy QUICK dog";
const replaced = string.replace(re, "<b>" + pattern + "</b>");
console.log(replaced);
which doesn't preserve the original casing, thus the need for '<b>$&</b>'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With