This post will discuss the procedure to split the name into the first name and last name using JavaScript.
How to Split a Full Name Into First and Last Using JavaScript?
For splitting a full name between the first name and last name, use the following JavaScript methods:
- split() method
- substring() method
Let’s examine these methods one by one.
Method 1: Split the Name Into First Name and Last Name Using split() Method
To split the name into its first name and last name/ surname, use the “split()” method. The split() method accepts a pattern and divides the String into an ordered list of substrings by searching for the pattern, then stores these substrings in an array and gives the array as an output.
Syntax
Use the following syntax for the split() method:
The separator is any character or pattern based on which the string will be split.
Return Value
- It returns an array of separated words based on the separator.
Example
Create a variable “name” that contains a full name:
Call the “split()” method and pass the “space” as a separator where the string will split:
Print the split string “name” as first name and last name using the array indexes. As we know that the split method returns an array of a list of words, so, access them using indexes:
console.log("Last Name = "+ names[1]);
The output shows that the name is successfully split into first name and last name:
Method 2: Split the Name Into First Name and Last Name Using substring() Method
Another method to split the name into the first name and the last name is the “substring()” method. The substring() method gives the portion of the string between the given start and end indexes or up to the string’s end.
Syntax
Follow the given syntax for the substring() method:
In the given syntax:
- The “startIndex” is the index of the character from where the substring will be started.
- “endIndex” is the end of the substring.
Return Value
- It outputs a new string containing the desired portion of the input string.
Example
Create a variable “space” that will store the index of the space using the “indexOf()” method:
Call the “substring()” method to get the first name from the name by passing the starting index as “0” and the end index is the index of the space:
To get the second part of the string or the last name, use the “substring()” method:
Print the first name and last name on the console:
console.log("Last Name = "+ lastName);
Output
We have provided the easiest method related to splitting a full name into first and last names in JavaScript.
Conclusion
To split a full name into two parts, first name and last name, use the “split()” method and “substring()” method. The split() method gives the array of split words in an ordered list of substrings, while the substring() method gives the string as a substring in between the start and the end indexes. This post discussed the procedure to split the name into two parts: first name and last name using JavaScript.