You can globally search for a "word" and check the length of the .match()
if a match is found:.
If two or more words are found, you're good:
var matches = string.match(/\b[^\d\s]+\b/g);
if ( matches && matches.length >= 2 )
{ /* Two or more words ... */ };
You can define a word as \b[^d\s]+\b
, which is a word boundary \b
, one or more non digits and non whitespaces [^d\s]+
, and another word boundary \b
. You have to make sure to use the global option g
for the regex to find all the possible matches.
You can tweak the definition of a word in your regex. The trick is to make use of the length
property of the .match()
, but you should not check this property if there are no matches, since it'll break the script, so you must do if (matches && matches.length ...)
.
Additionally it's quite simple to modify the above code for X
words where X
is either a number or a variable.
jsFiddle example with your 4 examples