Jasper
Jasper

Reputation: 5238

Exact matching using regexp

var name ='John Rock';
alert((/^John|Steve$/i).test(name));

http://jsfiddle.net/czBhb/

This code alerts true, because doesn't use an exact mathing, but has to.

Should return true for John and joHn (case matching off). But not for John 12 or mahjohng.

There is | in the code, we should keep it.

How do I fix this regexp?

Upvotes: 0

Views: 96

Answers (4)

Xavi López
Xavi López

Reputation: 27880

The point is in the ^ and $ delimiters. As already pointed out in the comments, they seem to have precedence over the OR, so your regex is matching anything that starts with John, or ends with Steve.

Put the delimiters outside the OR:

var name ='John Rock';
alert((/^(John|Steve)$/).test(name));

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074919

If your goal is to match exactly John or Steve, you want to put a group in there:

alert(/^(?:John|Steve)$/i.text(name));

Also note the i for case insensitivity. (I did point this out in my answer to your other question more than half an hour ago, as soon as Beat Richartz pointed out the problem.)

Upvotes: 3

Beat Richartz
Beat Richartz

Reputation: 9622

Try this:

alert(/^(?:John|Steve)$/i).test(name))

(?: groups between ^ and $ without actually creating the group

/i for the case insensitivity

Upvotes: 2

Udo Klein
Udo Klein

Reputation: 6902

What about

var name ='John Rock';
alert((/^(John|Steve)$/i).test(name));

Upvotes: 2

Related Questions