Question

I want to make the case insensitive matching part of value of query within value of s bold.

If I find query within s I can't simply do:

var s="New York";    
var query="new";

var result = s.replace(/query/i,'<strong>' + query + '</strong>';

Since then it will also replace the casing in s with the casing in query, which I don't want. I want to keep the casing as in s.

Result would have to be: "New York"

Was it helpful?

Solution

If you make it a capture group (by surrounding it with parentheses), then you can use the placeholder $1:

var s="New York";  
var result = s.replace(/(new)/i,'<strong>$1</strong>');
// result = <strong>New</strong> York

see live example: http://jsfiddle.net/2zau4/


As pointed out in comments - and something which I never knew about - is that you dont actually need the capture group as javascript uses characters $& to represent "the entire match". So you could also do this:

var s="New York";  
var result = s.replace(/new/i,'<strong>$&</strong>');
// result = <strong>New</strong> York

As a final note I assume you realise that you original syntax will not work:

var s="New York";    
var query="new";

var result = s.replace(/query/i,'<strong>' + query + '</strong>';
-----------------------^
This is searching for literal "query" not 
  the variable query (containing the string "new")

The correct syntax must create a RegExp from a string with the "i" flag:

var s="New York";    
var query="new";

var result = s.replace(new RegExp(query,'i'),'<strong>$&</strong>');

OTHER TIPS

var s="New York";    
var query="new";
var result = s.replace(new RegExp(query,"i"),function(match){
   return "<strong>" + match + "</strong>";
});

JS Fiddle: http://jsfiddle.net/F7Y8y/2/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top