Home > Mobile >  Javascript regular expression that allow only alphabet, space and - only
Javascript regular expression that allow only alphabet, space and - only

Time:11-23

I want a regular expression that allow only alphabet, one space after word, and - only it will not accept two word but single space after word allowed. Any ther special character are not allowed. Example

John -> true
John(space) -> true
John-Doe -> true
John-Doe(space) -> true
(space)John -> false
John Doe -> false

I am trying using this [a-zA-Z-][a-zA-Z -] But not working exactly. Please help.

CodePudding user response:

If you don't want to allow consecutive hyphens -- in the pattern, you might write the pattern as:

^[A-Z][a-z]  ?(?:-[A-Z][a-z]  ?)?$

Explanation

  • ^ Start of string
  • [A-Z][a-z] ? Match a char A-Z and 1 chars a-z followed by an optional space (or [A-Za-z] if you want to allow mixed chars)
  • (?:-[A-Z][a-z] ?)? Optionally match the same as the preceding pattern with a leading -
  • $ End of string

See a regex demo


If you want to allow all mixed chars with an optional space at the end:

^[A-Za-z-]  ?$

Regex demo

  • Related