Reputation: 1464
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?
Upvotes: 0
Views: 1084
Reputation: 3454
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]+$
Upvotes: 2
Reputation: 59232
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]+$
Upvotes: 3