DEV Community

101samovar
101samovar

Posted on

How to extract email-address from a string?

There is a string that contains email addresses.
To get the email addresses we need the match method.
The match method with a regular expression pattern for email addresses.
This pattern suppose that the email address consists of login name, at-symbol and domain name.
Login name can be combined from letters in lower and upper case, digits and underscore symbol.
Domain name should consist of two parts separated with a dot symbol.

let string = 'manager: Smith@sm-domain.net; sales: Mak@sm-domain.net';
let emailList = string.match(/[\w]+@[\w\-]+\.[\w]{2,}/g);
console.log(emailList);
Enter fullscreen mode Exit fullscreen mode

So we have got an array with email addresses from the string.


I hope you found this article useful, if you need any help please let me know in the comment section.

👋 See you next time. Have a nice day!

Subscribe to our channel:
https://www.youtube.com/c/Samovar101

Discussion (2)

Collapse
icawebdesign profile image
Ian.H

This has the typical "email addresses are simple foo@bar.baz format" issues. Email addresses can be extremely complex and there is no perfect pattern matching.

Have a look here for example:

emailregex.com/index.html
regular-expressions.info/email.html

You've made a lot of assumptions, so yes, your regex will match your described scenario, but your post title doesn't declare that it must require a strict email format to work. In fact, it will even fail a simple firstname.lastname@bar.baz address which is common.

IMO, especially as flagged as beginners will only help junior devs believe that email address parsing is simple, when it very much isn't.

Collapse
101samovar profile image
101samovar Author

You are absolutely right.
In general, parsing email is not a trivial task.
However, in many cases, using a generic regular expression is overkill.
For example: when parsing corporate mail with a fixed format.