简体   繁体   中英

JavaScript Regular Expression - Accept only two words with no special characters

I am trying this below pattern in http://regex101.com/#javascript

Pattern: [a-zA-Z]+\\s{1}[a-zA-Z]+

String: 'Testing Only two characters'

http://regex101.com/r/gT0uX9 highlights only first two words of the string but when I try it in a fiddle, it says true. What is the problem? Am I doing something wrong?

Fiddle

Because .test() checks whether the regex matches or not. In your case it is matching correctly and hence true

What the doc says:

Use test() whenever you want to know whether a pattern is found in a string (similar to the String.search method); for more information (but slower execution) use the exec method (similar to the String.match method). As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match.

( emphasis mine ) You can use anchors ^ and $ if you want only two words.

^[a-zA-Z]+\s{1}[a-zA-Z]+$

It returns true because your string contains a string of two words. If you want to check whether the string is a string of two words, use the anchors ^ and $ for start-of-string and end-of-string:

^[a-zA-Z]+\s{1}[a-zA-Z]+$

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