How to use a variable name in a regex?

Y

Yansky

Hi, if I have a string assigned to a variable, how can I use that
variable in a regex?

e.g. I would like to do something like this:
var words = 'the quick brown browning fox';
var key = getKey();
var patt=/\bkey\b/;
patt.test(words);

Unfortunately I can't just put the string I'm searching for directly
in the regex, because it will be changing each time this bit of the
script is run.

Any help would be appreciated.
Cheers.
 
M

Martin Honnen

Yansky said:
Hi, if I have a string assigned to a variable, how can I use that
variable in a regex?

e.g. I would like to do something like this:
var words = 'the quick brown browning fox';
var key = getKey();
var patt=/\bkey\b/;

Don't use a regular expression literal then, instead use the new RegExp
constructor
var patt = new RegExp("\\b" + key + "\\b");
 
Y

Yansky

Don't use a regular expression literal then, instead use the new RegExp
constructor
   var patt = new RegExp("\\b" + key + "\\b");

Thanks, I had tried new RegExp earlier but I forgot to escape the
backslashes.
Cheers.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top