Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use javascript to find email address in a string

What I am trying to do is to extract email address out of the string SomeName, First ([email protected])

Here is the code that I already tried:

 var stringToSearchIn="SomeName, First ([email protected])";


 var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

var extractedEmail=re.exec(stringToSearchIn);

The variable extractedEmail in the code returns a null.

like image 419
Foo Avatar asked Feb 28 '13 16:02

Foo


1 Answers

I tried this and failed

...is not a very useful description of what happenned. At a guess, the re failed to find a match. An obvious cause for this is the regex you've used here will only match a string which ONLY contains an email address - remove the end anchors (^,$) from the regex and you'll get your email address.

var re = /(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/;
like image 100
symcbean Avatar answered Oct 01 '22 11:10

symcbean