Help | Site Map
Connecting Tech Pros Worldwide
 
 
LinkBack Thread Tools
  #1  
Old October 14th, 2008, 05:15 PM
Yansky
Guest
 
Posts: n/a
Default How to use a variable name in a regex?

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.
  #2  
Old October 14th, 2008, 05:45 PM
Martin Honnen
Guest
 
Posts: n/a
Default Re: How to use a variable name in a regex?

Yansky wrote:
Quote:
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/
  #3  
Old October 14th, 2008, 07:55 PM
Yansky
Guest
 
Posts: n/a
Default Re: How to use a variable name in a regex?

On Oct 15, 3:38*am, Martin Honnen <mahotr...@yahoo.dewrote:
Quote:
Yansky wrote:
Quote:
Hi, if I have a string assigned to a variable, how can I use that
variable in a regex?
>
Quote:
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.
 

Bookmarks

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are Off
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over network members.
Post your question now . . .
It's fast and it's free

Popular Articles