4

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

1
  • you've created a regexp re ... and never use it ... so that's something you should look at - try const replaced = string.replace(re, "<b>" + pattern + "</b>"); Commented Sep 5, 2018 at 1:21

1 Answer 1

12

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.