Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - Get original value of string replace using regex

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.";
like image 621
dthree Avatar asked Dec 28 '13 21:12

dthree


1 Answers

You'd use regex capturing groups and backreferences to capture the match and insert it in the string

var searchRegex = new RegExp('('+userInput+')' , 'ig');
dynamicString = dynamicString.replace(searchRegex, '<span class="highlight">$1</span>');

FIDDLE

like image 136
adeneo Avatar answered Oct 12 '22 23:10

adeneo