hamburger
hamburger

Reputation: 1435

Space between two words

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?

Upvotes: 0

Views: 1896

Answers (3)

Smern
Smern

Reputation: 19086

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/

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382454

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]*$/

Upvotes: 2

fotanus
fotanus

Reputation: 20116

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

Upvotes: 0

Related Questions