简体   繁体   中英

JavaScript, regex: How to fetch mail address in mailto: links

Is there a jquery plugin or may be a regex which can be used to all the fields in query string of a mailto: link. It should support the mailto syntax .

Say if I have a link like ...

<a href="mailto:astark1@unl.edu,id@internet.node">Some msg</a>

The regex should give me the mail addresses in mailto: link - astark1@unl.edu , id@internet.node . It should also support links like

<a href="mailto:astark1@unl.edu?subject=Comments from MailTo Syntax Page">
<a href="mailto:astark1@unl.edu?body=I am having trouble finding information on">
<a href="mailto:astark1@unl.edu?subject=MailTo Comments&cc=ASTARK1@UNL.EDU&bcc=id@internet.node">

For a link like

<a href="mailto:value">tell a friend</a>

I would pass value and the function and get an associative array of email addresses and other fields passed in query string.

Parsing URLs, and especially their query strings, is not a job for regexes. You could use a proper URL-parsing library or perhaps just a query string parsing one .

I'm not sure how accurate this is, but it might be improved if you feel a necessity to use regex.

function getEmails(str) {
// returns a list of email addresses in 'str'
    var tags = str.match(/<a href=('|")mailto:(.*?)\1(.*?)>/gi);
    var res = [];
    if (!tags.length) return res;
    for (var i = 0; i < tags.length; i++) {
        tags[i] = tags[i].replace(/^<a href=('|")mailto:(.+?)(\?[^\1]*)?\1>$/,'$2');
        var arr = tags[i].replace(/\s/g,'').split(',');
        for (var j = 0; j < arr.length; j++) res.push(arr[j]);
    }
    return res;
}

I'm not sure what you mean in the last part by the way so I tried to answer the first part.

If you know what you are doing :

var href = 'mailto:hello@world.com?subject=My+Subject&body=My+Body';

function getMailto(s) {
    var r = {};
    var email = s.match(/mailto:([^\?]*)/);
            email = email[1] ? email[1] : false;
  var subject = s.match(/subject=([^&]+)/);
            subject = subject ? subject[1].replace(/\+/g,' ') : false;
    var body = s.match(/body=([^&]+)/);
            body = body ? body[1].replace(/\+/g,' ') : false;

  if(email) {r['email'] = email;}
  if(subject) {r['subject'] = subject;}
  if(body) {r['body'] = body;}

  return r;
}

console.log(getMailto(href));

Demo : https://jsfiddle.net/l2aelba/qov9wpk5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM