How to accept space in regex?
17,029
Just add a space or
\s
(to allow any space character like tab, carriage return, newline, vertical tab, and form feed) in the character class
^[a-zA-Z ]+$
Note: This will allow any number of spaces anywhere in the string.
If you want to allow only a single space between first name and last name.
^[a-zA-Z]+(?:\s[a-zA-Z]+)?$
-
^
: Start of the line anchor -
[a-zA-Z]+
: Match one or more letters -
(?:
: Non-capturing group -
\s[a-zA-Z]+
: Match one or more letters after a single space -
?
: allow previous group zero or one time -
$
: End of line anchor
input:valid {
color: green;
}
input:invalid {
color: red;
}
<input pattern="[a-zA-Z]+(?:\s[a-zA-Z]+)?" />
To allow multiple names/string separated by a space, use *
quantifier on the group.
^[a-zA-Z]+(?:\s[a-zA-Z]+)*$
^
Related videos on Youtube
Author by
Marius
Updated on September 14, 2022Comments
-
Marius over 1 year
I have this regex:
const name_regex = /^[a-zA-Z]+$/;
I tested this with the following regex tool
Can you please tell me how to do to accept and space?
Accept eg:
John Smith
Thanks in advance!
-
Gerald Schneider about 8 yearsNote that
\s
matches every whitespace character including tabs, newlines etc.