Extract the Name from an Email Address in JavaScript

avatar

Borislav Hadzhiev

Thu Nov 18 20212 min read

Extract the Name from an Email Address #

To extract the name from an email address, use the split() method to split the email on the @ symbol and access the first array element, e.g. email.split('@')[0]. The split method will return an array containing the two strings, where the first string stores the name.

index.js
const email = 'johndoe@email.com'; const result = email.split('@')[0]; console.log(result); // ๐Ÿ‘‰๏ธ "johndoe"

The only parameter we passed to the String.split method is a separator.

For our purposes, we have to split the string on the @ symbol.

index.js
const email = 'johndoe@email.com'; // ๐Ÿ‘‡๏ธ ['johndoe', 'email.com'] console.log(email.split('@'));

The first string from the results contains the username, which we can access using an index of 0.

Indexes are zero-based in JavaScript. The index of the first element in the array is 0, and the index of the last - array.length - 1.

Note that if the @ symbol is not contained in the string, you'd get an array containing the entire string as a parameter.

index.js
const email = 'johndoeemail.com'; // ๐Ÿ‘‡๏ธ ['johndoeemail.com] console.log(email.split('@'));

If you need to handle this scenario, you can use an if statement.

index.js
const email = 'johndoeemail.com'; let name = ''; if (email.indexOf('@') !== -1) { name = email.split('@')[0]; } console.log(name); // ๐Ÿ‘‰๏ธ ""

We used the String.indexOf method to check if the @ symbol is contained in the string.

If the provided substring is contained in the string, the method returns the index of the first occurrence.

If it's not contained in the string, the method returns -1.

We only reassign the name variable, if the @ symbol is contained in the string.

An alternative approach is to use the String.slice method.

To get the name from an email address, call the slice() method on the string and extract the characters from index 0, up to the index of the @ symbol, e.g. email.slice(0, email.indexOf('@')). The slice method will return a new string containing the name.

index.js
const email = 'johndoe@email.com'; const result = email.slice(0, email.indexOf('@')); console.log(result); // ๐Ÿ‘‰๏ธ "johndoe"

We passed the following 2 parameters to the String.slice method:

  1. start index - the index of the first character to be included in the new string
  2. end index - go up to, but not including this index

The slice method returns a new string that contains the characters from index 0, up to, but not including the @ symbol.

Which approach you pick is a matter of personal preference. I'd go with the split method, as it is a little more concise and direct.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee