0

I want a JS regex that only matches names with capital letters at the beginning of each word and lowercase letters thereafter. (I don't care about technical accuracy as much as visual consistency — avoiding people using, say, all caps or all lower cases, for example.)

I have the following Regex from this answer as my starting point.

/^[a-z ,.'-]+$/gmi

Here is a link to the following Regex on regex101.com.

As you can see, it matches strings like jane doe which I want to prevent. And only want it to match Jane Doe instead.

How can I accomplish that?

Let Me Tink About It
  • 13,762
  • 16
  • 86
  • 184

2 Answers2

3

Match [A-Z] initially, then use your original character set afterwards (sans space), and make sure not to use the case-insensitive flag:

/^[A-Z][a-z,.'-]+(?: [A-Z][a-z,.'-]+)*$/g

https://regex101.com/r/y172cv/1

You might want the non-word characters to only be permitted at word boundaries, to ensure there are alphabetical characters on each side of, eg, ,, ., ', and -:

^[A-Z](?:[a-z]|\b[,.'-]\b)+(?: [A-Z](?:[a-z]|\b[,.'-]\b)+)*$

https://regex101.com/r/nP8epM/2

CertainPerformance
  • 313,535
  • 40
  • 245
  • 254
1

If you want a capital letter at the beginning and lowercase letters following where the name can possibly end on one of ,.'- you might use:

^[A-Z][a-z]+[,.'-]?(?: [A-Z][a-z]+[,.'-]?)*$
  • ^ Start of string
  • [A-Z][a-z]+ Match an uppercase char, then 1+ lowercase chars a-z
  • [,.'-]? Optionally match one of ,.'-
  • (?: Non capturing group
    • [A-Z][a-z]+[,.'-]? Match a space, then repeat the same pattern as before
  • )* Close group and repeat 0+ times to also match a single name
  • $ End of string

Regex demo

The fourth bird
  • 127,136
  • 16
  • 45
  • 63