How to split First name and Last name in JavaScript
Short article to separate first name and last name in a form field using split method in JavaScript.
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
Related Posts
Press Shift + Enter for new Line in Textarea
Override default textarea behavior on Enter key press without Shift, prevent new lines, and take custom actions like submitting forms instead. Still allow Shift+Enter newlines.
in vs hasOwnProperty(): Differences in Inherited Properties
The article explains the differences between JavaScript's 'in' operator and 'hasOwnProperty()' method. And also learn the use cases of both in JS.
How to Fix "ReferenceError: document is not defined" in JavaScript
The "ReferenceError: document is not defined" is a common error in JavaScript that occurs when trying to access the `document` object in a non-browser environment like Node.js.
How to Fix the "Cannot Read Property of Undefined" Error in JavaScript
The "Cannot read property of undefined" error occurs when you try to access a property or method of a variable that is undefined in JavaScript.
