Skip to content

Instantly share code, notes, and snippets.

@injms
Created December 4, 2017 14:56
Show Gist options
  • Select an option

  • Save injms/9cd8e0e5ce85d8656562d2cd73c51902 to your computer and use it in GitHub Desktop.

Select an option

Save injms/9cd8e0e5ce85d8656562d2cd73c51902 to your computer and use it in GitHub Desktop.
A port of WordPress's antispambot function from PHP to JavaScript
let getRandomIntInclusive = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
}
let zeroise = (number, threshold) => {
if (number.length === threshold) {
return number;
}
else {
let padding = [];
for (var i = 1; i < threshold; i++) {
padding.push('0');
}
return padding.join('') + number;
}
};
let dechex = (number) => {
// discuss at: http://locutus.io/php/dechex/
// original by: Philippe Baumann
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// improved by: http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript
// input by: pilus
// example 1: dechex(10)
// returns 1: 'a'
// example 2: dechex(47)
// returns 2: '2f'
// example 3: dechex(-1415723993)
// returns 3: 'ab9dc427'
if (number < 0) {
number = 0xFFFFFFFF + number + 1
}
return parseInt(number, 10)
.toString(16)
}
let antispambot = (emailAddress, hexEncoding = 0) => {
let emailNoSpamAddress = [];
for (let i in emailAddress) {
let j = getRandomIntInclusive(0, 1) + hexEncoding;
// let j = 0;
// let j = 1;
// let j = 2;
if (j == 0) {
emailNoSpamAddress.push('&#' + emailAddress.charCodeAt(i));
}
else if (j == 1) {
emailNoSpamAddress.push(emailAddress[i]);
}
else if (j == 2) {
emailNoSpamAddress.push('%' + zeroise(dechex(emailAddress.charCodeAt(i)), 2));
}
}
return emailNoSpamAddress.join('').replace('@', '&#64;');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment