3

Here is the original webapp - http://mathiasbynens.be/demo/email-obfuscator#code

I'm converting it to JavaScript app -

function obfuscate_email() {
  var email = document.OBFUSCATOR.email.value,
    output = "";
  if (!email) {
    alert("Please enter an email address.");
  } else {
    if (document.OBFUSCATOR.reverse.checked) {
      email = email.split("").reverse().join("");
      output = "<span class=\"email\">";
    }
    if (document.OBFUSCATOR.encode.checked) {
      for (var i = 0; i < email.length; i++) {
        output += "&#" + email.charCodeAt(i) + ";";
      }
    } else {
      output += email;
    }
    if (document.OBFUSCATOR.reverse.checked) {
      output += "</span>";
    }

    document.getElementById("output").value = document.OBFUSCATOR.link.checked ? "<a href=\"&#109;&#97;&#105;&#108;&#116;&#111;&#58;" + output + "\">" + output + "</a>" : output;
    document.getElementById("preview").innerHTML = document.getElementById("output").value;
  }
}

But it doesn't work properly when all the checkboxes are checked. How can I fix this?

It doesn't work because output becomes <span class="email">html code</span> and this function makes output the href attribute.

user3079292
  • 97
  • 1
  • 7

1 Answers1

1

To reverse a string in JavaScript, don’t use email.split("").reverse().join("") — use Esrever (online demo):

esrever.reverse('foo@example.com');
// → 'moc.elpmaxe@oof'

To encode text using HTML entities, you could use the he JavaScript library (online demo).

he.encode('foo@example.com', {
  'encodeEverything': true
});
// → '&#x66;&#x6F;&#x6F;&#x40;&#x65;&#x78;&#x61;&#x6D;&#x70;&#x6C;&#x65;&#x2E;&#x63;&#x6F;&#x6D;'

// or, to encode the already-reversed email address:
he.encode('moc.elpmaxe@oof', {
  'encodeEverything': true
});
// → '&#x6D;&#x6F;&#x63;&#x2E;&#x65;&#x6C;&#x70;&#x6D;&#x61;&#x78;&#x65;&#x40;&#x6F;&#x6F;&#x66;'

To answer your question, try not setting innerHTML as that will effectively undo the HTML-encoding. Set .textContent instead.

Community
  • 1
  • 1
Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248