6

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
  • Have you tried userInput.toLowerCase()... Commented Dec 28, 2013 at 21:31
  • Wouldn't work, because if the user searched 1366 Mulberry Lane, the matching result will then show all lowercase, when it should be Proper Cased. Commented Dec 28, 2013 at 21:40

2 Answers 2

12

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

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

7 Comments

It may be preferable to escape certain characters which have meaning in RegExp or HTML, e.g. <>[]?^$
Wow. 8 years of web development and somehow I have never, ever heard of backreferences or seen their use. +100.
@Paul S., If you look at my code above, you'll see I already do that.
@PaulS. - there's an escaping replace() on the user input in the OP's code, so I figured that was already taken care of.
@dc2 - now you know how they work, and it can be really useful sometimes
|
0

You can use it without capturing groups too.

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

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.