Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

regex - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...