I am looking for a regular expression to check that there are at least two words in my input field.
I tried this:
var spaceReg = /^\\w+\\s\\w+$/
It works fine but if I have three or more words, not anymore (or if I have a word like this meyer-miller).
My next try was this:
/^(?:[\\w-]+ ?)*$/
but this works also if I have a space at the end of the first word and with single words.
Is there an expert here for help?
Simply don't add the start and end of string markers :
var spaceReg = /\w\s+\w/
If you also want to ensure you have nothing else than words and spaces, then you can use
var spaceReg = /^\w+\s+\w[\w\s]*$/
If you want to allow spaces at start (not sure from your question) and dash (from the comments), use
var spaceReg = /^\s*[\w-]+\s+[\w-][\w-\s]*$/
EDIT: I originally thought you wanted words separated by dash to match.. try this: http://jsfiddle.net/YbWYp/8/
var spaceReg = /[\-\w]+\s[\-\w]+/
EDIT: also, if you just want to make sure that you have some space within some non-space somewhere in your string you are testing, you could do something as simple as: http://jsfiddle.net/YbWYp/10/
var pattern = /\S\s\S/
1.8.7 :004 > "asd asdasd "=~ /\w+(\s\w+)+/
=> 0
1.8.7 :005 > "asd asdasd"=~ /\w+(\s\w+)+/
=> 0
1.8.7 :006 > "asd asdasd asd"=~ /\w+(\s\w+)+/
=> 0
1.8.7 :007 > "asd"=~ /\w+(\s\w+)+/
You can add * at the right side of \\s to support multiple spaces
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.