将纯文本电子邮件转换为可点击链接 - REGEX/jQuery

EHe*_*man 5 regex hyperlink

我试图将纯文本电子邮件地址转换为表格内的可点击邮件链接.

我有以下功能,将找到的链接转换为mailto链接,但它似乎只适用于第一个找到的链接.任何后续链接(第2次,第3次出现等)仍保留为纯文本链接.我似乎无法弄清楚我可能做错了什么.任何帮助将非常感激!

代码:

HTML

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
   <div class='filter-email-box'>
   <div>This is a sample text which contains john@gmail.com </div>
   <div>This text contains two emails adam@example.com and paul@example.com </div>
</div>
Run Code Online (Sandbox Code Playgroud)

使用Javascript

$(".filter-email-box div").filter(function(){
   var html = $(this).html();
   var emailPattern = /[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/;  

   var matched_str = $(this).html().match(emailPattern);
   if(matched_str){
       $(this).html(html.replace(emailPattern,"<a href='mailto:"+matched_str+"'>"+matched_str+"</a>"));
       return $(this)
   }    
})
Run Code Online (Sandbox Code Playgroud)


以下是我设置的小提琴:http: //jsfiddle.net/z6LF5/

hwn*_*wnd 6

使用g(全局)修饰符(查找所有匹配项而不是在第一个匹配项后停止)。

您可以执行以下操作:

$('.filter-email-box div').ready(function() {
  $('.filter-email-box div').each(function() {
     var html  = $(this).html();
     var regex = /([a-z0-9._-]+@[a-z0-9.-]+\.[a-z]{2,4})/ig
     var text  = html.replace(regex, "<a href='mailto:$1'>$1</a>");
     $(this).html(text);
  });
});
Run Code Online (Sandbox Code Playgroud)

小提琴


blo*_*les 6

当有多个电子邮件地址时,JQuery方法match返回一个数组(当设置全局搜索标志时g),因此我们循环遍历该数组(matched_str在本例中称为)并替换匹配的电子邮件.

$(".filter-email-box div").filter(function () {
    var html = $(this).html();
    var emailPattern = /[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/g;  

    var matched_str = $(this).html().match(emailPattern);
    if ( matched_str ) {
      var text = $(this).html();
      $.each(matched_str, function (index, value) {
          text = text.replace(value,"<a href='mailto:"+value+"'>"+value+"</a>");
      });
      $(this).html(text);
      return $(this)
    }    
})
Run Code Online (Sandbox Code Playgroud)

的jsfiddle