網站 email 防爬蟲字串產生器

by brecht

HTML

<script>
  //填入網站所使用的 email
  var email = "service@example.com";
  //填入該 email 所使用的 HTML 片段  
  var template = '<a href="mailto:{{email}}" class="email_style">{{email}}</a>';

  var EmailMixer = {
    mix: function(email, template) {
      this.template = template.replace(/{{email}}/g, this.toCharNo(email));
      var arr = this.revert(this.template);
      return arr.join(";");
    },
    toCharNo: function(str) {
      var code = "";
      for (var i = 0; i < str.length; i++) {
        code += ("|" + str[i].charCodeAt() + ";");
      }
      return code;
    },
    revert: function(str) {
      var reverseArr = [];
      var encodeStr = "";
      var isEnCodeStr = false;

      while (str) {
        theChar = str[0];

        if (isEnCodeStr === true) {
          if (theChar !== ";") {
            encodeStr += theChar;
          } else {
            isEnCodeStr = false;
            reverseArr.unshift(encodeStr);
            encodeStr = "";
          }
        } else {
          if (theChar === "|") {
            isEnCodeStr = true;
            encodeStr += theChar;
          } else {
            reverseArr.unshift(theChar);
          }
        }
        str = str.substr(1);
      }
      return reverseArr;
    }
  }

  document.write(EmailMixer.mix(email, template));

</script>