One more AntiSpam JavaScript

I often see how people struggle with email addresses like myemail [at] mycomain [dot] com.

This is fine on forums and other sites where you cannot emit your JavaScript code, but it is really frustrating to see such emails on the Contact Me-like pages on different sites.

I just obfuscate the emails in JavaScript so people can click the links and the same time avoid any spam.

Lots of different email obfuscators are available in Internet. They can do it online, so you can just copy-past the JS generated. But I just come up with my own JavaScript antispam tool that I like.

Let's have a look at part of HTML:

Contact Us: <a id="myMail">MyEmail [at] MyDomain [dot] com</a>

Then we have the JavaScript somewhere on a page:

antiSpam.mailTo('myMail', {
  email: 'MyEmail',  
  domain: ['MyDomain', 'com'],  
  //name: 'Support',  
  nameAsEmail: true

This will make a cliackable MAILTO link which is much more friendly for users. If the browser doesn't support JavaScript it will do nothing and leave default ANCHOR tag. So the email will be visible, but not clickable and not friendly.

The mailTo function has two parameters. First - the ID of the anchor tag which should be modified. The second parameter is actually set of options. Bolded are required parameters to make it working:

  • email - the email's recipient string or array. If it's an array - the resulting address will be separated with dots. For example:
    • email: 'support'.
    • email: ['dmitriy', 'nagirnyak'].
  • domain - the recipient's domain name string or array. If it's an array - the resulting domain will be separated with dots. For example:
    • domain: ''.
    • domain: ['MyDomain', 'com'].
  • name - the text to be shown on the link. If not specified test will not be modified or will be the same as full email address. See next option:
  • nameAsEmail - if the name is not specified and this one is set, then text of the link will become the actual email address.

The actual JavaScript code (that should be included/embedded of course into the page) is:

var antiSpam = {
    toSeparatedString: function(obj, delimiter) {
        if (!obj) return null;
        if (typeof(obj) == 'string') return obj;
        var res = '';
        for (var i=0; i<obj.length; i++) {
            if (i > 0 && delimiter) res += delimiter;
            res += obj[i];
        return res;
    mailTo: function(id, parameters) {        
        if (!parameters) return;
        var a = document.getElementById(id);
        if (!a) return;
        var email = this.toSeparatedString(, '.');
        if (!email) return;
        var domain = this.toSeparatedString(parameters.domain, '.');
        if (!domain) return;
        email = email + '@' + domain;
        a.href = 'mailto:' + email;
        if (! {
            if (parameters.nameAsEmail) {
                a.innerHTML = email;
            a.innerHTML =;

Happy coding!