Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I perform a case insensitive replace in JavaScript?

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

like image 569
Mary Avatar asked Dec 24 '22 04:12

Mary


1 Answers

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

like image 71
CertainPerformance Avatar answered Jan 13 '23 13:01

CertainPerformance