0

The string contains a name, where the first part corresponds to the name and the second to the lastname.

The regular expression must verify these formats:

  • "Surname1 Surname2, Name1 Name2"
  • "Surname1, Name1 Name2 Surname2"

Invalid strings:

 "Surname1 Surname2 Name1 Name2" 
 "Surname1, Surname2, Name1 Name2"
 "Surname1 Surname2 Name1 Name2,"

I try the following: /([\w][\,][\s]{1}\b)/, but did not work

I appreciate any help.

Carlos Laspina
  • 2,013
  • 4
  • 27
  • 44

3 Answers3

1

You can use this regex:

/\b\w+\s+\w+\s*,\s*\w+\s+\w+\b/
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

If you want to support numbers in the name like your example above.

var validName = function (name) {
  return /^\w+ \w+, \w+ \w+$/.test(name);
};

or if any kind of whitespace is allowed between names

validName = function (name) {
  return /^\w+\s\w+,\s\w+\s\w+$/.test(name);
},

or if you only want to allow US letters

validName = function (name) {
  return /^[A-Za-z]+ [A-Za-z]+, [A-Za-z]+ [A-Za-z]+$/.test(name);
},
0

I found a solution that verifies both cases:

This is the regular expression: /\b\w+\s*\w*,\s\w+\s\w+\s*\w*\s*\w*\s*\w*\s*\w*$\b/

Carlos Laspina
  • 2,013
  • 4
  • 27
  • 44