How to split First name and Last name in JavaScript

featured Image

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

Capitalize First Letter of a String in JavaScript

String interpolation in JavaScript

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *