JavaScript Regex does not match exact string

In the example below, the output is true. It is a cookie and it also matches cookie14214 I assume that the cookie is in the cookie14214 line. How can I hone this cookie just to get a 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); 
+7
source share
2 answers

The answer depends on your consideration of the characters associated with the word cookie . If the word should appear strictly on one line, then:

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

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

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

The second regular expression is 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 ) 
+5
source

Yes, or use word boundaries. Please 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 cookie string, then you don’t even need regular expressions, just use == as /^cookie$/i.test(s) basically matches s.toLowerCase() == "cookie" .

+2
source

All Articles