Usually, when people first start dealing with user input, they have to parse information such as a person’s name. I know I have had to do this at some point in almost every language that I have programmed in. One of the best ways to go about parsing a full name to get the first name, middle name (if available), and last name is to use a regular expression. Let’s say that we have
John J. Jinklehiemer-Smith in a variable called
var fullName = " John J. Jinklehiemer-Smith "; var reName = /(\w+)\s+(?:(\w(?=\.)|\w+(?:-\w+)?)\s+)?(\w+(?:-\w+)?)/; var matches = fullName.match(reName); var firstName = matches; // "John" var middleName = matches; // "J." var lastName = matches; // "Jinklehiemer-Smith"
Basically, the regular expression searches for at least a first name followed by a last name that may or may not be hyphenated. If a middle name (which may also be hyphenated or abbreviated) was specified, it will also be captured. One issue that I have with the above solution is the fact that names in the
var reName = /(\w+(?:-\w+)?),\s*(\w+)(?:\s+(\w(?=\.)|\w+(?:-\w+)?))?|(\w+)\s+(?:(\w(?=\.)|\w+(?:-\w+)?)\s+)?(\w+(?:-\w+)?)/; var fullName = prompt("Full name #1:", " David Richard Wade "); var matches = fullName.match(reName); var firstName = matches || matches; // "David" var middleName = matches || matches; // "Richard" var lastName = matches || matches; // "Wade" fullName = prompt("Full name #2:", "Smith, Carmen Bea-paz"); matches = fullName.match(reName); firstName = matches || matches; // "Carmen" middleName = matches || matches; // "Bea-paz" lastName = matches || matches; // "Smith"
Ok, I know that regular expression is long, but it definitely beats parsing the string with
James London · December 20, 2012 at 10:36 AM
Thanks for the regex, works great, but I’m having trouble adjusting it. it does a great job ignoring prefixes and suffices. Curious how I would adjust to capture them, if present.
stat · December 10, 2014 at 7:53 AM
Won’t quite work with names that contain apostrophes, such as O’Connor and O’Neil.