Javascript regex: check username

Of these questions: javascript regex: only English letters are allowed

How can I do this expression test for the name of people? Currently, it does not allow spaces between names at all. I need to be able to match something like John Doe

Greetings

+3
source share
5 answers

let result = /^[a-zA-Z ]+$/.test( 'John Doe');
console.log(result);
Run code

Drop any characters you need in the character class. That's why I said specifically about what you want to check. This regular expression will not take into account accented characters if you are not indifferent that you are more likely to approach a unicode match.

+12

FWIW, :

let name = "John Doe";
let result = name.replace(/[^A-Za-z0-9_'-]/gi, '');
console.log(result);

, ', , -', , "", Engle; drop user; . , , , , .

+5

:

/^(([A-Za-z]+[\-\']?)*([A-Za-z]+)?\s)+([A-Za-z]+[\-\']?)*([A-Za-z]+)?$/

[ 1 , "" ] . , , . , ( , , , ), , + . , , , . ( , , DRY.)

:

"Jon Doe": true
"Jonathan Taylor Thomas": true
"Julia Louis-Dreyfus": true
"Jean-Paul Sartre": true
"Pat O'Brien": true
"Þór Eldon": false
"Marcus Wells-O'Shaugnessy": true
"Stephen Wells-O'Shaugnessy Marcus": true
"This-Is-A-Crazy-Name Jones": true
"---- --------": false
"'''' ''''''''": false
"'-'- -'-'-'-'": false
"a-'- b'-'-'-'": false
"'-'c -'-'-'-d": false
"e-'f g'-'-'-h": false
"'ij- -klmnop'": false

Note that it still does not handle Unicode characters, but it could be extended to include the ones you need.

+4
source
^\s*([A-Za-z]{1,}([\.,] |[-']| ))+[A-Za-z]+\.?\s*$

Similar to @Stephen_Wylie's solution, but shorter (better?).

+1
source

Just add a space

^[\w ]+$

Not sure if you need it.

0
source

Source: https://habr.com/ru/post/1750761/


All Articles