7

In the example below the output is true. It cookie and it also matches cookie14214 I'm guessing it's because cookie is in the string cookie14214. How do I hone-in this match to only get cookie?

var patt1=new RegExp(/(biscuit|cookie)/i);
document.write(patt1.test("cookie14214"));

Is this the best solution?

var patt1=new RegExp(/(^biscuit$|^cookie$)/i);
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424

2 Answers2

6

The answer depends on your allowance of characters surrounding the word cookie. If the word is to appear strictly on a line by itself, then:

var patt1=new RegExp(/^(biscuit|cookie)$/i);

If you want to allow symbols (spaces, ., ,, etc), but not alphanumeric values, try something like:

var patt1=new RegExp(/(?:^|[^\w])(biscuit|cookie)(?:[^\w]|$)/i);

Second regex, explained:

(?:                 # non-matching group
    ^               # beginning-of-string
    | [^\w]         # OR, non-alphanumeric characters
)

(biscuit|cookie)    # match desired text/words

(?:                 # non-matching group
    [^\w]           # non-alphanumeric characters
    | $              # OR, end-of-string
)
newfurniturey
  • 37,556
  • 9
  • 94
  • 102
  • have you tested this? i dont think you can use the negative lookahead after the desired string. – jbabey Aug 22 '12 at 19:36
  • @jbabey Yeah, tested with firebug; also, the regexes are not using any lookaheads (positive, or negative). The second one is using a non-matching group, `(?:`, if that's what you're confusing with `(?!` – newfurniturey Aug 22 '12 at 19:39
  • @jbabey It's a good one to use; it works like it's name implies - the regex has to match that group also, but it doesn't return it in the list of matches. So, the return-array would only contain two groups (first is the "full context" of the match, second is the matched word). – newfurniturey Aug 22 '12 at 19:44
2

Yes, or use word boundaries. Note that this will match great cookies but not greatcookies.

var patt1=new RegExp(/(\bbiscuit\b|\bcookie\b)/i);

If you want to match the exact string cookie, then you don't even need regular expressions, just use ==, since /^cookie$/i.test(s) is basically the same as s.toLowerCase() == "cookie".

João Silva
  • 89,303
  • 29
  • 152
  • 158