How to convert the full name into first last, middle name in javascript example
- Admin
- Mar 10, 2024
- Javascript Typescript
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 names into first, last, and middle names 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 strings into salutations, firstname, Lastname,middlename, and suffixes.
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 in first and last name
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 names into salutations, first names, middle names, last names, and suffixes. It includes a split function, using regular expression and the humanparser
npm library.