By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,848 Members | 3,202 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,848 IT Pros & Developers. It's quick & easy.

How to use a variable name in a regex?

P: n/a
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.
Oct 14 '08 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Yansky wrote:
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");

--

Martin Honnen
http://JavaScript.FAQTs.com/
Oct 14 '08 #2

P: n/a
On Oct 15, 3:38*am, Martin Honnen <mahotr...@yahoo.dewrote:
Yansky wrote:
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");

--

* * * * Martin Honnen
* * * *http://JavaScript.FAQTs.com/
Thanks, I had tried new RegExp earlier but I forgot to escape the
backslashes.
Cheers.
Oct 14 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.