In a given string, I’m trying to verify that there are at least two words, where a word is defined as any non-numeric characters so for example
// Should pass
Phil D'Sousa
Billy - the - Kid
// Should Fail
Joe
454545 354434
I thought this should work:
(\b\D*?\b){2,}
But it does not.
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:
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 optiongfor 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
lengthproperty of the.match(), but you should not check this property if there are no matches, since it’ll break the script, so you must doif (matches && matches.length ...).Additionally it’s quite simple to modify the above code for
Xwords whereXis either a number or a variable.jsFiddle example with your 4 examples