Foo
Foo

Reputation: 4596

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.

Upvotes: 6

Views: 17989

Answers (4)

massquote
massquote

Reputation: 4607

This one works for me.

var searchInThisString ="SomeName, First ([email protected]) SomeName2, First2 ([email protected])";

var foundEmails =[];

var emailRegex = /(([^<>()[\]\\.,;:\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 gotcha;

while (match = emailRegex.exec(searchInThisString)){

     //-- store in array the found match email
     foundEmails.push(match[0]);

    //-- remove the found email and continue search if there are still emails
    searchInThisString= searchInThisString.replace(match[0],"")
}

alert(foundEmails.join(" "))

Upvotes: 0

Marcel Korpel
Marcel Korpel

Reputation: 21763

No need for a regex here. If the string is always of the format

Name (email)

You can simply use ( as delimiter:

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

var extractedEmail = stringToSearchIn.substr(stringToSearchIn.indexOf('(') + 1).slice(0, -1);

Upvotes: 1

simple-thomas
simple-thomas

Reputation: 729

Try this regex

@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"

This will accept any of the following:

and so on...

Upvotes: -1

symcbean
symcbean

Reputation: 48357

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,}))/;

Upvotes: 7

Related Questions