简体   繁体   English

JavaScript,正则表达式:如何在mailto中获取邮件地址:链接

[英]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. 是否有一个jquery插件或一个正则表达式,可用于mailto:链接的查询字符串中的所有字段。 It should support the mailto syntax . 它应该支持mailto语法

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 . 正则表达式应该给我mailto中的邮件地址:link- astark1@unl.eduid@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. 我将传递value和函数,并获得在查询字符串中传递的电子邮件地址和其他字段的关联数组。

Parsing URLs, and especially their query strings, is not a job for regexes. 解析URL,尤其是其查询字符串,不是正则表达式的工作。 You could use a proper URL-parsing library or perhaps just a query string parsing one . 您可以使用适当的URL解析库,也可以仅使用解析一个查询字符串

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/ 演示: https : //jsfiddle.net/l2aelba/qov9wpk5/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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