Split a Full Name into First and Last in JavaScript

avatar

Borislav Hadzhiev

Last updated: Aug 29, 2022

banner

Photo from Unsplash

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 space.
  2. String.split() will return an array containing the names.
  3. Use array destructuring to assign the values of the first and last names to variables.
index.js
const fullName = 'Adam Jones'; // 👇️ ['Adam', 'Jones'] const [first, last] = fullName.split(' '); console.log(first); // 👉️ Adam console.log(last); // 👉️ Jones

We used the String.split method to get an array containing the names.

We split the string on the spaces to get the values of the names in the resulting array.

We used array destructuring to assign to the first and last variables on the same line.

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

Alternatively, you can manually access the array elements when assigning to the variables.

index.js
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

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
const fullName = 'Adam Douglas Jones'; const [first, middle, last] = fullName.split(' '); console.log(first); // 👉️ Adam console.log(middle); // 👉️ Douglas console.log(last); // 👉️ Jones

Here is the same example but using index lookup.

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

Which approach you pick is a matter of personal preference. I'd go with using array destructuring as I find it more concise and just as readable.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.