0
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?

Jasper
  • 5,090
  • 11
  • 34
  • 41
  • 1
    Possible duplicate of [Regex - Match whole string](http://stackoverflow.com/q/6298566/851811). – Xavi López Feb 25 '13 at 13:37
  • Apparently `|` has lower operator precedence than `^` and `$`, which is a little counterintuitive. So you need to wrap `John|Steve` in parentheses, in order to apply the `|` before the `^` and `$` anchors. – mellamokb Feb 25 '13 at 13:38
  • I already pointed out how to do this in [my answer to your earlier question](http://stackoverflow.com/a/15066690/157247) more than half an hour ago, as soon as Beat Richartz pointed out the problem. – T.J. Crowder Feb 25 '13 at 13:39

4 Answers4

3

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

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

What about

var name ='John Rock';
alert((/^(John|Steve)$/i).test(name));
Udo Klein
  • 6,784
  • 1
  • 36
  • 61
2

Try this:

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

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

/i for the case insensitivity

Beat Richartz
  • 9,474
  • 1
  • 33
  • 50
1

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));
Xavi López
  • 27,550
  • 11
  • 97
  • 161