Convert text email to interactive link - REGEX / jQuery

I am trying to translate plain text email addresses into interactive links to links within a table.

I have the following function that converts found links to mailto links, but it seems that it works only for the first link found. Any subsequent links (2nd, 3rd occurrence, etc.) remain as text links. I can’t understand what I can do 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 john@gmail.com </div>
   <div>This text contains two emails adam@example.com and paul@example.com </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)
   }    
})


Here is the fiddle I set up: http://jsfiddle.net/z6LF5/

+5
source share
3 answers

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

JSFiddle

+6

g (global), ( , ).

:

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

+4

if anyone is interested i translated jquery code to vanilla js code

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

Sample link: http://jsfiddle.net/eliz82/q0x4tjr3/

0
source

Source: https://habr.com/ru/post/1544948/


All Articles