How to accept space in regex? [duplicate]
Asked Answered
T

1

7

I have this regex:

const name_regex = /^[a-zA-Z]+$/;

I tested this with the following regex tool

link

Can you please tell me how to do to accept and space?

Accept eg: John Smith

Thanks in advance!

Translate answered 19/2, 2016 at 7:31 Comment(1)
yes,anywhere in the inputTranslate
B
18

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.

RegEx Demo

If you want to allow only a single space between first name and last name.

^[a-zA-Z]+(?:\s[a-zA-Z]+)?$
  1. ^: Start of the line anchor
  2. [a-zA-Z]+: Match one or more letters
  3. (?:: Non-capturing group
  4. \s[a-zA-Z]+: Match one or more letters after a single space
  5. ?: allow previous group zero or one time
  6. $: End of line anchor

RegEx Demo

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]+)*$
                         ^

RegEx Demo

Barye answered 19/2, 2016 at 7:31 Comment(1)
Note that \s matches every whitespace character including tabs, newlines etc.Breechcloth

© 2022 - 2024 — McMap. All rights reserved.