Reputation: 5238
var name ='John Rock';
alert((/^John|Steve$/i).test(name));
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
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
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
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
Reputation: 6902
What about
var name ='John Rock';
alert((/^(John|Steve)$/i).test(name));
Upvotes: 2