{

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


In some cases, the UI form on a page accepts only a single text box to take the full name, the developer needs 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, the user enters the name with three words.

for example, the 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 the 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, salutation, and suffix with humanparser in nodejs

humanparser is an npm library used to parse human name string into salutation, 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 names into different names is completed. In this post, You learned to 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.