Borislav Hadzhiev
Mon Oct 04 2021·2 min read
Photo by Joseph Young
To split a full name into first and last names in JavaScript:
String.split
method on the string, splitting on the empty spaceString.split
returns an array containing the names// 👉️ 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.
// 👉️ 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:
// 👉️ 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:
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