How to convert fullname into first last and middle name in javascript example


In some cases, UI form on a page accepts only single text box to take full name, developer need to split this into first name,middle name and lastname.

This article talks about how to split full name into first,last and middle name in javascript and Angular

usually user enter the name with three words.

for example user entered in name filed as

let fullname ="john Erwin Wick "
var names=fullname.split(' ');
console.log("firstname="+names[0])
console.log("lastName="+names[1]);
console.log("middleName="+names[2]);

what if user entered two words

if (names.length > 2) {
  output = [{firstname: names[0], middlenames: names.slice(1, -1).join(' ') , lastname: names[names.length - 1]}]; 
}
else if (names.length < 2) {
  output = [{firstname: names[0], middlenames: '', lastname: ''}];
}
else {
  output = [{firstname: names[0], middlenames: '', lastname: names[names.length - 1]}];
}

Split full name into first,last,saluation and suffix with humanparser in nodejs

humanparser is a npm library used to parse human name string into saluation,firstname,lastname,middlename and suffix.

First Install humanparser using npm install

npm install humanparser

Here is an example

const parser = require('humanparser');

const names = parser.parseName("Mr. first second last");
console.log(names);

Output

 {
    salutation: 'Mr.',
    firstName: 'first',
    lastName: 'last',
    middleName: 'second',
    fullName: 'Mr first second last'
}

using regular expression into firstname and lastname

using regular expression in javascript, we can split using.

const fullname = "First Second Third"
  var namesArray  = fullname.match(/[A-Z][a-z]+|([aeodlsz]+\s+)+[A-Z[a-z]+/g) || [];


console.log("first name  : " + s[0]);
console.log("middle name : " + s[1]);
console.log("last name: " + s[2]);

Conclusion

Learned different ways to parse full name into different names is completed. In this post, You learned split full name into salutation, first name, middle name, last name and suffix. It includes split function, using regular expression and humanparser npm library

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.