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/
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With