Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert plain text email to clickable link - REGEX/jQuery

I am trying to convert plain text email addresses into clickable mailto links inside of a table.

I have the following function that is converting found links into mailto links, but it only seems to work for the first found link. Any subsequent links (2nd, 3rd occurrence etc.) remain as plain text links. I can't seem to figure out what I might be doing wrong. Any help would be much appreciated!

The code:

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 [email protected] </div>
   <div>This text contains two emails [email protected] and [email protected] </div>
</div>

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)
   }    
})


Heres the fiddle I've setup: http://jsfiddle.net/z6LF5/

like image 366
EHerman Avatar asked Jun 17 '14 16:06

EHerman


1 Answers

When there's more than one email address, JQuery method match returns an array (when the global search flag g is set), so we're looping over that array (called matched_str in this case) and replacing the matching emails.

$(".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)
    }    
})

JSFiddle

like image 190
bloodyKnuckles Avatar answered Sep 25 '22 02:09

bloodyKnuckles