How to obfuscate an e-mail address on a website with JavaScript?

Obfuscating an email address on a website with JavaScript involves converting the email address into a format that is not easily recognizable by email harvesting bots, while still allowing it to be interpreted correctly by human users.

One common approach is to replace characters with their HTML entity equivalents.

Here’s a basic example of how you can obfuscate an email address using JavaScript:

HTML:

<!-- Placeholder element to display obfuscated email -->
<p id="obfuscatedEmail"></p>

JavaScript:

// Function to obfuscate email address
function obfuscateEmail(email) {
    let obfuscated = '';
    for (let i = 0; i < email.length; i++) {
        // Convert character to HTML entity
        obfuscated += '&#' + email.charCodeAt(i) + ';';
    }
    return obfuscated;
}

// Original email address
const email = '[email protected]';

// Obfuscate the email address
const obfuscated = obfuscateEmail(email);

// Display the obfuscated email address
const obfuscatedEmailElement = document.getElementById('obfuscatedEmail');
obfuscatedEmailElement.innerHTML = 'Obfuscated Email: ' + obfuscated;

In this code, we define a function obfuscateEmail that takes an email address as input and returns an obfuscated version of it.

Inside the function, we iterate over each character of the email address and convert it into its corresponding HTML entity using charCodeAt() to get the character code.

Next we then concatenate these HTML entities to form the obfuscated email address.

Then we call the obfuscateEmail function with the original email address, and display the obfuscated email address in an HTML element.

Keep in mind that while this method helps obfuscate the email address from bots, it may still be decipherable by determined attackers.

Additionally, it’s important to consider accessibility concerns, as obfuscating email addresses may make them difficult for screen readers to interpret.