In this short article, we will learn to split the first name and last name from a name string using JavaScript.
Sometimes we want to separate the name string entered by a user in a form to its first and second name before storing it in our database.
So to split the first and last names of a person, we use the split()
method in JavaScript
The split()
method is used to split a string into an array of substrings and returns a new array. The original string is not changed using this method.
We pass a separator
to the split()
method to tell Javascript at which character or point we want our string to split.
Syntax:
string.split(separator)
Now using this method we can separate the first and last name from a string.
Example:
const name = "John Wick"
const nameArr = name.split(" ");
const firstName = nameArr[0];
const lastName = nameArr[1];
console.log(`First Name: ${firstName}, Last Name : ${lastName}`)
Output:
First Name: John, Last Name: Wick
In the above example, we have to use the split()
method and passed a blank space " "
as the separator to split the name string.
Once we got the array of substrings in nameArr, we used the index
to get the first and the last name of the string.
Related Topics:
Split string after a specific character using JavaScript
Replace all occurrences of a string in JavaScript