Convert all static text email addresses to mailto links using jQuery

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:

Posted on by Joe in JavaScript, jQuery

6 Responses to Convert all static text email addresses to mailto links using jQuery

  1. Antony Carthy

    Thank you – exactly what I needed, worked first time.

  2. Tauseef

    Great work! Exactly what i was looking for.

    Thanks

  3. Tung Pham

    Thanks a ton, worked like a charm.

  4. Adam

    This script only converts the first email address to a “mailto” link. How can the script be changed to get every email address on a page?

  5. Joe

    Hi Adam

    It does replace them all, you probably have a problem with you selector. Are you using my code exactly or your own version?

    Cheers
    Joe

  6. Adam

    After searching for a couple hours yesterday, I came across another script that works. In your script, I changed the selector to that of my main content area (#content), and the script still only picked up the first of 5 email addresses on the page. No worries. I got the issue fixed. Thanks for your help, Joe! :)

Add a Comment