Sometimes, we want to extract the user name from an email address using JavaScript.
In this article, we’ll look at how to extract the user name from an email address using JavaScript.
How to extract the user name from an email address using JavaScript?
To extract the user name from an email address using JavaScript, we can use a regex to get the part before the @
with the string match
method.
For instance, we write:
const str = "someone@example.com";
const nameMatch = str.match(/^([^@]*)@/);
console.log(nameMatch)
to call str.match
with /^([^@]*)@/
to get the part of the email address before the @
.
Therefore, nameMatch
is ['someone@', 'someone', index: 0, input: 'someone@example.com', groups: undefined]
.
Conclusion
To extract the user name from an email address using JavaScript, we can use a regex to get the part before the @
with the string match
method.