EHerman
EHerman

Reputation: 1903

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/

Upvotes: 5

Views: 6220

Answers (3)

crisc2000
crisc2000

Reputation: 1222

if anyone is interested I translated the jquery code to vanilla JS code

var elem = document.querySelector('.filter-email-box');
var html = elem.innerHTML;
if (html) {
  var regex = /([a-z0-9._-]+@[a-z0-9.-]+\.[a-z]{2,4})/ig;
  elem.innerHTML = html.replace(regex, '<a href="mailto:$1">$1</a>');
}

Demo link: https://jsfiddle.net/q0x4tjr3/

Upvotes: 1

bloodyKnuckles
bloodyKnuckles

Reputation: 12089

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

Upvotes: 8

hwnd
hwnd

Reputation: 70732

Use the g (global) modifier which ( finds all matches rather than stopping after the first match ).

You could implement the following:

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

Fiddle

Upvotes: 6

Related Questions