Reputation: 3132
I have a string condition in js where i have to check whether name entered in text box contains with one space only.
pattern: name.status === 'full_name' ? /^[a-zA-Z.+-.']+\s+[a-zA-Z.+-. ']+$/ : /^[a-zA-Z.+-. ']+$/
But the above regex matches names ending with 2 spaces also.
I need to match it such that the entered name should accept only one space for a name string. So the name will have only one space in between or at the end.
Upvotes: 1
Views: 3583
Reputation: 626870
Two observations: 1) \s+
in your pattern matches 1 or more whitespaces, and 2) [+-.]
matches 4 chars: +
, ,
, -
and .
, it is thus best to put the hyphen at the end of the character class.
You may use
/^[a-zA-Z.+'-]+(?:\s[a-zA-Z.+'-]+)*\s?$/
See the regex demo
Details
^
- start of string[a-zA-Z.+'-]+
- 1 or more letters, .
, +
, '
or -
(?:\s[a-zA-Z.+'-]+)*
- zero or more sequences of:
\s
- a single whitespace[a-zA-Z.+'-]+
- 1 or more letters, .
, +
, '
or -
chars\s?
- an optional whitespace$
- end of string.Note: if the "names" cannot contain .
and +
, just remove these symbols from your character classes.
Upvotes: 1
Reputation: 14179
you could also use word boundaries...
function isFullName(s) {
return /^\b\w+\b \b\w+\b$/.test(s);
}
['Giuseppe', 'Mandato', 'Giuseppe Mandato']
.forEach(item => console.log(`isFullName ${item} ? ${isFullName(item)}`))
Upvotes: 0
Reputation: 300
/^\S+\s\S+$/
try this
Some explanations:
Upvotes: 0