1

For example, suppose I have the following text:

"Constants cons are CONTAGIOUS"

I want all the "cons" replaced irrespective of case, but preserving case on the replace.

For example, suppose I want to put bold tags around them, I would want the output to be:

"<b>Con</b>stants <b>cons</b> are <b>CON</b>TAGIOUS"

In JavaScript, I have tried:

var re = new RegExp("con", 'ig');
var newText = text.replace(re,"<b>" + "con" + "</b>");

This does a case insensitive search but I lose the case on the replace. Is there a way to preserve case on the replace?

Mary
  • 1,005
  • 2
  • 18
  • 37

2 Answers2

4

As @JordanRunning has pointed out in a comment, a simple solution is to refer to the matched string in the replacement string using $&:

"Constants cons are CONTAGIOUS".replace(/con/ig, "<b>$&</b>")

Produces:

"<b>Con</b>stants <b>con</b>s are <b>CON</b>TAGIOUS"

Another alternative (my original suggestion) it using capturing group (con), and reference it in the replacement string with $1:

"Constants cons are CONTAGIOUS".replace(/(con)/ig, "<b>$1</b>")
janos
  • 120,954
  • 29
  • 226
  • 236
4

You can wrap the input in a capturing group () and refer back to it in the replacement via $1:

var text = "Constants cons are CONTAGIOUS";

var regex = new RegExp("(con)", 'ig');
var newText = text.replace(regex, "<b>$1</b>");

console.log(newText); // "<b>Con</b>stants <b>con</b>s are <b>CON</b>TAGIOUS"

Edit: Thanks @JordanRunning, you don't even need a capturing group in this case, since you are referring back to the complete match:

var text = "Constants cons are CONTAGIOUS";

var regex = new RegExp("con", 'ig');
var newText = text.replace(regex, "<b>$&</b>");

console.log(newText); // "<b>Con</b>stants <b>con</b>s are <b>CON</b>TAGIOUS"
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94