SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Hybrid View

  1. #1
    SitePoint Addict
    Join Date
    Jun 2006
    Location
    Durban, South Africa
    Posts
    287
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Regular expressions in JS

    Hi all

    Im having a little problem with a regular expressions. Here is the code

    Code:
      var pattern = new RegExp("(^|\s)match_me(\s|$)");
    
      if(pattern.test("match_me something_else"))
        alert('match');
      else
        alert('no match');
    I cant figure out why this doesn't work, well to my understanding this should work...
    Iv also tried

    Code:
      var pattern = new RegExp("(^|\s|\b)match_me(\b|\s|$)");
    And it also doesn't work.

    Can anyone help?
    Thanks in advance

  2. #2
    SitePoint Addict
    Join Date
    Jun 2006
    Location
    Durban, South Africa
    Posts
    287
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi. I have sort of got it to work, but with some new problems

    If I create the pattern without inverted commas " it works, like so

    Code:
      var pattern = /\bmatch_me\b/;
    
      if(pattern.test("match_me something_else"))
        alert('match');
      else
        alert('no match');
    This will match, but the pattern needs to be dynamic (ie. match_me could be anything)

    So how can I create the pattern dynamically?

  3. #3
    SitePoint Addict
    Join Date
    Jun 2006
    Location
    Durban, South Africa
    Posts
    287
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi again for the 3rd and hopefully last time.

    I got it

    Change the pattern to the following

    Code:
      var search_for = 'match_me';
      var pattern = new RegExp("\\b" + search_for + "\\b");
    And it works

  4. #4
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    You shouldn't use \b to find the word breaks because that includes other word separators, like the hyphen or underscore, which means that match_me will also match match_me_now

    Going from your original code, if you don't need a custom string in the regex then you should regex delimiters instead of building one from a string.

    If you do create a new regex object, then you'll need to escape any slashes that you have in there.

    Code javascript:
    // The preferred method
    var pattern = /(^|\s)match_me(\s|$)/;
    // Or, with a custom string
    var pattern = new RegExp('(^|\\s)' + text + '(\\s|$)');
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •