Let Me Tink About It
Let Me Tink About It

Reputation: 16102

JS regex for proper names: How to force capital letter at the start of each word?

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?

Upvotes: 0

Views: 1485

Answers (3)

Mohamed
Mohamed

Reputation: 469

Here's my solution to this problem

const str = "jane dane"

console.log(str.replace(/(^\w{1})|(\s\w{1})/g, (v) => v.toUpperCase()));

So first find the first letter in the first word (^\w{1}), then use the PIPE | operator which serves as an OR in regex and look for the second block of the name ie last name where the it is preceded by space and capture the letter. (\s\w{1}). Then to close it off with the /g flag you continue to run through the string for any iterations of these conditions set.

Finally you have the function to uppercase them. This works for any name containing first, middle and lastname.

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163187

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

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370589

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

Upvotes: 3

Related Questions