How to Split Full Name into First and Last in JavaScript

Javascript split full name example; In this tutorial we will show you how to split fullname into first, middle and last name in javascript;

In javascript to breaking the name or line we can use String.split methods; This methods can break the string to array format to all words; You can break/split string with space, comma or any special character.

Example 1:

We split the string on an empty space in order to get the values of the names in the resulting array.

// Supported in IE 6-11
const fullName = 'Virat Kohli';

const splitFullName = fullName.split(' ');
console.log(splitFullName); // ['Virat', 'Kohli']

const first = splitFullName[0];
const last = splitFullName[1];

console.log(first); // Virat
console.log(last); // Kohli

Example 2:

You can use the split your string as something like this;

// Not Supported in IE 6-11
const fullName = 'Virat Kohli';

const [first, last] = fullName.split('  '); // ['Adam', 'Jones']

console.log(first); // Virat
console.log(last); // Kohli

Example 3:

Here’s an example of splitting a full name that contains 3 names and assigning the values to variables:

// Supported in IE 6-11
const fullName = 'Virat Anushka Kohli';

const splitFullName = fullName.split(' ');
console.log(splitFullName); // ['Virat','Anushka', 'Kohli']

const first = splitFullName[0];
const middle = splitFullName[1];
const last = splitFullName[1];

console.log(first); //  Virat
console.log(middle); //  Anushka
console.log(last); // Kohli

I hope these examples help you.