encodeEmailAddress.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. * Created by Estevao on 12-01-2015.
  3. */
  4. /**
  5. * Input: an email address, e.g. "foo@example.com"
  6. *
  7. * Output: the email address as a mailto link, with each character
  8. * of the address encoded as either a decimal or hex entity, in
  9. * the hopes of foiling most address harvesting spam bots. E.g.:
  10. *
  11. * <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101;
  12. * x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111;
  13. * &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a>
  14. *
  15. * Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
  16. * mailing list: <http://tinyurl.com/yu7ue>
  17. *
  18. */
  19. showdown.subParser('encodeEmailAddress', function (addr) {
  20. 'use strict';
  21. var encode = [
  22. function (ch) {
  23. return '&#' + ch.charCodeAt(0) + ';';
  24. },
  25. function (ch) {
  26. return '&#x' + ch.charCodeAt(0).toString(16) + ';';
  27. },
  28. function (ch) {
  29. return ch;
  30. }
  31. ];
  32. addr = 'mailto:' + addr;
  33. addr = addr.replace(/./g, function (ch) {
  34. if (ch === '@') {
  35. // this *must* be encoded. I insist.
  36. ch = encode[Math.floor(Math.random() * 2)](ch);
  37. } else if (ch !== ':') {
  38. // leave ':' alone (to spot mailto: later)
  39. var r = Math.random();
  40. // roughly 10% raw, 45% hex, 45% dec
  41. ch = (
  42. r > 0.9 ? encode[2](ch) : r > 0.45 ? encode[1](ch) : encode[0](ch)
  43. );
  44. }
  45. return ch;
  46. });
  47. addr = '<a href="' + addr + '">' + addr + '</a>';
  48. addr = addr.replace(/">.+:/g, '">'); // strip the mailto: from the visible part
  49. return addr;
  50. });