Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Regex does not match exact string

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);
like image 801
ThomasReggi Avatar asked Aug 22 '12 19:08

ThomasReggi


People also ask

How do you match exact strings?

We can match an exact string with JavaScript by using the JavaScript string's match method with a regex pattern that has the delimiters for the start and end of the string with the exact word in between those.

What does \+ mean in regex?

Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol. Example: "^a" matches "a" at the start of the string. Example: "[^0-9]" matches any non digit.


2 Answers

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
)
like image 188
newfurniturey Avatar answered Oct 07 '22 14:10

newfurniturey


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".

like image 44
João Silva Avatar answered Oct 07 '22 16:10

João Silva