Jeff
Jeff

Reputation: 1800

Splitting Name into last name, first name, middle initial

I have a user input from a textbox that contains a user's name

input can look like this:

var input = "Doe, John M";

However, input can be a whole lot more complex. like:

var input = "Doe Sr, John M"

or "Doe, John M"

or "Doe, John, M"

or even "Doe Sr, John,M"

What I'd like to do is separate the last name (with the sr or jr) the first name, and then the middle initial.

So, these strings become :

var input = "Doe#John#M" or "Doe Sr#John#M" or "Doe#John#M"

I've tried this regular expression,

input = input.replace(/\s*,\s*/g, '#'); but this doesn't take into account the last middle initial.

Upvotes: 0

Views: 6669

Answers (3)

chovy
chovy

Reputation: 75666

Checkout humanparser on npm.

https://www.npmjs.org/package/humanparser

Parse a human name string into salutation, first name, middle name, last name, suffix.

Install

npm install humanparser

Usage

var human = require('humanparser');

var fullName = 'Mr. William R. Jenkins, III'
    , attrs = human.parseName(fullName);

console.log(attrs);

//produces the following output

{ saluation: 'Mr.',
  firstName: 'William',
  suffix: 'III',
  lastName: 'Jenkins',
  middleName: 'R.',
  fullName: 'Mr. William R. Jenkins, III' }

Upvotes: 4

MikeM
MikeM

Reputation: 13631

The following seems to match your requirements

input = input.replace(/\s*,\s*|\s+(?=\S+$)/g, '#');

Upvotes: 2

pseudosavant
pseudosavant

Reputation: 7234

I'm sure this can probably be done via RegEx but splitting the string into arrays is often faster and a little less complex (IMO). Try this function:

var parseName = function(s) {
  var last = s.split(',')[0];
  var first = s.split(',')[1].split(' ')[1];
  var mi = s[s.length-1];

  return {
    first: first,
    mi: mi,
    last: last
  };    
};

You call it just passing in the name e.g. parseName('Doe, John M') and it returns an object with first, mi, last. I created a jsbin you can try that tests the formats of names you show in your question.

Upvotes: 4

Related Questions