Search This Blog

Javascript: parse a string of email addresses and contact names

A string contains contact name and email, like below
"Jake Smart" , jack@smart.com, "Development, Business"

We want to parse it into an array of objects (the object has name and email attributes):


// the parser function
function parse(s){
    var os = [];
    var regex = /(?:"([^"]+)")? ?<?(.*?@[^>,]+)>?,? ?/g;
    while(m=regex.exec(s)){
        os.push({name:m[1],email:m[2]});
    }
    return os;
}

// the code below is to test the parser function
var str = '"Jake Smart" <jake@smart.com>, jack@smart.com, "Development, Business" <bizdev@smart.com>';
var objects = parse(str);
for(var i=0;i<objects.length;i++){
    var object = objects[i];
    document.write(object.name + " : " + object.email + "<br/>");
}

See also Javascript: RegEx.exec() method

No comments:

Post a Comment