简体   繁体   中英

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?

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

What about

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

Try this:

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

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

/i for the case insensitivity

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM