JavaScript Regex does not match exact string

ThomasReggi picture ThomasReggi · Aug 22, 2012 · Viewed 10.5k times · Source

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);

Answer

newfurniturey picture newfurniturey · Aug 22, 2012

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
)