SitePoint Sponsor |
|
User Tag List
Results 1 to 4 of 4
Thread: Regular expressions in JS
-
Aug 13, 2008, 03:41 #1
- 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');
Iv also tried
Code:var pattern = new RegExp("(^|\s|\b)match_me(\b|\s|$)");
Can anyone help?
Thanks in advance
-
Aug 13, 2008, 04:09 #2
- 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');
So how can I create the pattern dynamically?
-
Aug 13, 2008, 04:14 #3
- 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");
-
Aug 13, 2008, 15:20 #4
- 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