Jquery从字符串

时间:2017-02-03 11:09:53

标签: jquery

我有一个字符串,其中可能包含多个电子邮件地址,我想检索它们并将它们包装在<a href='mailto: [EMAIL-HERE]'></a>中,用于字符串中的每个地址。​​

我知道Regexp通常是实现这一目标的最佳方式。我从这里的另一篇文章中找到了一些代码,几乎可以解决这个问题:

function checkIfEmailInString(text) {

        var regExp = /(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/;
        var matches = regExp.exec(text);

        return matches;
    }

但是一旦我在字符串中找到匹配项,我想用<a>包装的等价物替换电子邮件地址。正如我所说,它需要处理字符串中可能有多个电子邮件地址然后返回包含电子邮件的整个字符串的情况。有什么建议吗?

更新

示例字符串:

var string = "john (john@email.com) deals with the fruit and peter Secretary-IUR-Info@email.co.uk is the secretary of information"

1 个答案:

答案 0 :(得分:1)

检查这是否适合你

var str = "john (john@email.com) deals with the fruit and peter Secretary-IUR-Info@email.co.uk is the secretary of information";

str = str.replace(/[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+/gi, function(matched){
  return '<a href="mailto:'+matched+'">'+matched+'</a>';
});

https://jsfiddle.net/1hjLpdfm/2/

更新:我注意到你提供的正则表达式也正常运行,你最后错过了全局标志

var regExp = /(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/g;