In this post I’ll show how to use jQuery to automatically convert all email addesses from static text into a mailto link.
Consider the following table which contains a person’s details including their email address.

Using jQuery I can easily find table cells that contain an email address by using a regular expression and then convert the address into a mailto link:
$().ready(function() {
    var regEx = /(\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)/;

    $("table td").filter(function() {
        return $(this).html().match(regEx);
    }).each(function() {
        $(this).html($(this).html().replace(regEx, "<a href=\"mailto:$1\">$1</a>"));

First I’ve defined my email regular expression. I have also made sure the entire expression is in brackets, this sets up a regular expression group for the whole thing which I use when doing the replace.
For my example I’m only going to replace email addresses within a TD tag so my selector first gets these elements. I next use the filter function to only select the email address content from the TD by using the JavaScript match function with my email regular expression. I then iterate over the collection of elements and use the JavaScript replace function to replace the static email address with a mailto hyperlink to the same email address.
In my replace string I’m using $1, which will output the matching text from the original string from the first grouping in my regular expression. As I said earlier I put brackets around my entire regular expression so that the first grouping it the whole thing. This means that $1 will output the matched email address.
Now when I run my project the email addresses are automatically mailto links:


Post a Comment