Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out emails and names out of a string in javascript

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!

like image 748
Marc Avatar asked Dec 10 '22 17:12

Marc


2 Answers

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)

like image 84
Tracker1 Avatar answered Dec 29 '22 00:12

Tracker1


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 here

like image 20
karim79 Avatar answered Dec 28 '22 23:12

karim79