How to create Safe mailto links using JQuery

Here is a small piece of code that you can use to create safe mailto (spam emails free) links in your web application,


Firstly you need to create a link which is in the example below

<a href="info[at]example[dot]com"></a>
<a href="info[at]example[dot]com">Custom Text</a> 
 
As you can see, we have replaced @ with [at] and . with [dot], Now we will use JQuery to loop through all the links and do the exact opposite.

$(document).ready(function() {
    $('a[href*="[at]"][href*="[dot]"]').each(function() {
    var addr = $(this).attr('href').split('[at]').join('@').split('[dot]').join('.');
    $(this).attr('href', 'mailto:' + addr.toLowerCase());
    if ($(this).text().length == 0) $(this).text(addr);
   });
  });
 
This JQuery code will generate the following links.

<a href="mailto:info@example.com">info@example.com</a> 
 
<a href="mailto:info@example.com">Custom Text</a>
 
 

Comments

Popular posts from this blog

Inserting and Moving elements inside Ruby Array

Difference between Validations, Callbacks and Observers