JS - Get original value of string replace using regex

Viewed 3601

We have a string:

var dynamicString = "This isn't so dynamic, but it will be in real life.";

User types in some input:

var userInput = "REAL";

I want to match on this input, and wrap it with a span to highlight it:

var result = " ... but it will be in <span class='highlight'>real</span> life.";

So I use some RegExp magic to do that:

// Escapes user input,
var searchString = userInput.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");

// Now we make a regex that matches *all* instances 
// and (most important point) is case-insensitive.
var searchRegex = new RegExp(searchString , 'ig');

// Now we highlight the matches on the dynamic string:
dynamicString = dynamicString.replace(reg, '<span class="highlight">' + userInput + '</span>');

This is all great, except here is the result:

console.log(dynamicString);
// -> " ... but it will be in <span class='highlight'>REAL</span> life.";

I replaced the content with the user's input, which means the text now gets the user's dirty case-insensitivity.

How do I wrap all matches with the span shown above, while maintaining the original value of the matches?

Figured out, the ideal result would be:

// user inputs 'REAL',

// We get:
console.log(dynamicString);
// -> " ... but it will be in <span class='highlight'>real</span> life.";
2 Answers

You can use it without capturing groups too.

dynamicString = text.replace(new RegExp(userInput, 'ig'), '<span class="highlight">$&</span>');
Related