Split a Full Name into First and Last in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 04 20212 min read

banner

Photo by Joseph Young

Split a Full Name into First and Last Names #

To split a full name into first and last names in JavaScript:

  1. Call the String.split method on the string, splitting on the empty space
  2. String.split returns an array containing the names
  3. Use Array destructuring to assign the variables to the values of the array elements
index.js
// ๐Ÿ‘‰๏ธ Not Supported in IE 6-11 const fullName = 'Adam Jones'; // ๐Ÿ‘‡๏ธ ['Adam', 'Jones'] const [first, last] = fullName.split(' '); console.log(first); // ๐Ÿ‘‰๏ธ Adam console.log(last); // ๐Ÿ‘‰๏ธ Jones

In the code snippet, we used the String.split method to get an array containing the names.

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

We used Array Destructuring to assign the name variables on the same line.

An easy way to think about it is, the first and last variables got assigned the values of the first and second array elements.

Note that array destructuring is not supported in Internet Explorer 6-11, if you have to support the browser, manually assign the variables instead.
index.js
// ๐Ÿ‘‰๏ธ Supported in IE 6-11 const fullName = 'Adam Jones'; // ๐Ÿ‘‡๏ธ ['Adam', 'Jones'] const splitOnSpace = fullName.split(' '); console.log(splitOnSpace); const first = splitOnSpace[0]; const last = splitOnSpace[1]; console.log(first); // ๐Ÿ‘‰๏ธ Adam console.log(last); // ๐Ÿ‘‰๏ธ Jones

The code snippet shows the same approach, but instead of using array destructuring we assign the first and last variables by index lookups.

The concept is the same if the full name you're storing contains 3 names.

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

index.js
// ๐Ÿ‘‰๏ธ Not Supported in IE 6-11 const fullName = 'Adam Douglas Jones'; const [first, middle, last] = fullName.split(' '); console.log(first); // ๐Ÿ‘‰๏ธ Adam console.log(middle); // ๐Ÿ‘‰๏ธ Douglas console.log(last); // ๐Ÿ‘‰๏ธ Jones

Similarly, if you need to support IE, you can manually assign the array elements to variables:

index.js
const fullName = 'Adam Douglas Jones'; // ๐Ÿ‘‡๏ธ ['Adam', 'Douglas', 'Jones'] const splitOnSpace = fullName.split(' '); const first = splitOnSpace[0]; const middle = splitOnSpace[1]; const last = splitOnSpace[2]; console.log(first); // ๐Ÿ‘‰๏ธ Adam console.log(middle); // ๐Ÿ‘‰๏ธ Douglas console.log(last); // ๐Ÿ‘‰๏ธ Jones
Even if you don't need to support Internet Explorer 6-11, some people find that manually assigning the variables is more readable and intuitive. It's a matter of personal preference.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee