Ian Vink
Ian Vink

Reputation: 68740

javascript regular expressions with variables?

I am trying to execute a regular expression with a variable as the query.

//This works
$('body *').replaceText(/\b(Toronto)/gi, nameWrapper );

I need to have "Toronto" in a variable

var query = "Toronto";
$('body *').replaceText(/\b( --  query VARIABLE HERE --  )/gi, nameWrapper );

Upvotes: 2

Views: 2742

Answers (2)

Gumbo
Gumbo

Reputation: 655169

You need to use RegExp to build a regular expression from a string:

var query = "Toronto";
$('body *').replaceText(RegExp("\\b(" + query + ")", "gi"), nameWrapper);

And to quote your string properly, you can use this:

RegExp.quote = function(str) {
    return str.replace(/(?=[\\^$*+?.()|{}[\]])/g, "\\");
}

Then just use RegExp.quote(query) instead of query when building the regular expression:

var query = "Toronto";
$('body *').replaceText(RegExp("\\b(" + RegExp.quote(query) + ")", "gi"), nameWrapper);

Upvotes: 8

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

Try like this:

var query = 'Toronto';
var regex = new RegExp('\\b(' + query + ')', 'gi');
$('body *').replaceText(regex, nameWrapper);

Upvotes: 2

Related Questions