Modifying the regex pattern at runtime

Discussion in 'Javascript' started by Robert Oschler, Aug 1, 2005.

  1. One of the things that has always thrown me about Javascript regular
    expression patterns, is that you don't include quotes around them. So how
    can I modify a regex pattern at runtime. For example, given:

    var regexPattern = /.*?\s/i;

    Suppose I want to change the whitespace character to a comma, based on a
    variable being true or false?

    // This doesn't work, the string var double-quotes cause the match() method
    to find nothing.
    var delimChar = "/s";

    if (commaDelimited)
    delimChar = ",";

    var regexPattern = "/.*?" + delimChar + "/i";

    var matches = theString.match(regexPattern);

    So what is the proper syntax?

    Thanks.
    Robert Oschler, Aug 1, 2005
    #1
    1. Advertising

  2. You can use the RegExp object to create a regular expression from a
    string.

    var oRegExp = new RegExp("pattern");

    var aMatched = sString.match(oRegExp);
    michael elias, Aug 1, 2005
    #2
    1. Advertising

  3. "michael elias" <> wrote in message
    news:...
    > You can use the RegExp object to create a regular expression from a
    > string.
    >
    > var oRegExp = new RegExp("pattern");
    >
    > var aMatched = sString.match(oRegExp);
    >


    Michael,

    Thanks! That does it.
    Robert Oschler, Aug 1, 2005
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Xah Lee
    Replies:
    1
    Views:
    940
    Ilias Lazaridis
    Sep 22, 2006
  2. Xah Lee
    Replies:
    8
    Views:
    462
    Ilias Lazaridis
    Sep 26, 2006
  3. Xah Lee
    Replies:
    2
    Views:
    218
    Xah Lee
    Sep 25, 2006
  4. Replies:
    2
    Views:
    394
  5. ChrisC
    Replies:
    4
    Views:
    170
    ChrisC
    Jun 25, 2010
Loading...

Share This Page