How to use a variable name in a regex?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Yansky

    #1

    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.
  • Martin Honnen

    #2
    Re: How to use a variable name in a regex?

    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/

    Comment

    • Yansky

      #3
      Re: How to use a variable name in a regex?

      On Oct 15, 3:38 am, Martin Honnen <mahotr...@yaho o.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.

      Comment

      Working...