views:

51

answers:

3

I am using a cool widget to import email addresses out of gmail/homail/yahoo etc. The widget is still beta and I guess thats why it does not allow a lot of configuration. It actually just fills a textarea with the following data:

"Name one" <[email protected]>, "Name Two" <[email protected]>, "And so on" <[email protected]>

So I wondered if someone could help me write a regex or something like that to get all values out ofa string into an array. The desired format would be:

[{name: 'Name one', email: 'foo@domain'},{name: 'Name Two', email: 'foo@domain'},{name: 'And so on', email: '[email protected]'}]

I am a total regex noob and I have no clue on how to do that in javascript. Thanks for your help!

+1  A: 

In order to acheive that you'll have to read some documentation. Regex are not very complicated, but they get some gettin used to.

Here's a nice place to start: http://www.regular-expressions.info/javascript.html

And try practicing writting regex using http://rubular.com

marcgg
+1  A: 
function findEmailAddresses(StrObj) {
        var separateEmailsBy = ", ";
        var email = "<none>"; // if no match, use this
        var emailsArray = StrObj.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
        if (emailsArray) {
            email = "";
            for (var i = 0; i < emailsArray.length; i++) {
                if (i != 0) email += separateEmailsBy;
                email += emailsArray[i];
            }
        }
        return email;
    }

Source: http://javascript.internet.com/forms/extract-email.html

karim79
And if my email address is Håkan.Söderström@malmö.se? ;-) (See: http://stackoverflow.com/questions/3232/how-far-should-one-take-e-mail-address-validation/300862#300862 )Also, don't forget that `+` is a valid character for the name. Gmail users like to filter their emails `with [email protected]`
Sean Vieira
Then, it probably won't work. :)
karim79
That said, I don't think any regex is perfectly suited to this particular purpose, but do I think this answer does demonstrate the theory of operation of extracting emails from an arbitrary string.
karim79
I am sorry. I missformulated the question a little bit: It is not important to check wheter an email address is correct or not. The widget will only return valid emails. What I don't understand is to get the pairs of data (name + email). I would like to find out what is inside "" => name and what is inside <> = email. string.match does only find one at a time. right?
Marc
+1  A: 
function GetEmailsFromString(input) {
  var ret = [];
  var email = /\"([^\"]+)\"\s+\<([^\>]+)\>/g

  var match;
  while (match = email.exec(input))
    ret.push({'name':match[1], 'email':match[2]})

  return ret;
}

var str = '"Name one" <[email protected]>, ..., "And so on" <[email protected]>'
var emails = GetEmailsFromString(str)

Tracker1
thank you tracker! exactly what I was looking for!
Marc