Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript regular expression that allow only alphabet, space and – only

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading