This is a simple JavaScript function that will mask your email address following this pattern:
- If it’s not an email, the input string will be returned without modification.
- If the first part of the email is shorter than 4 characters, the entire username will be masked (me@example.com => *@e*****e.com)
- If the domain part of the email is shorter than 4 symbols, the entire domain will be masked
(username@abc.com => u******e@***.com - The TLD part (.com/.net/.org and etc) is never masked
- If the input string contains multiple emails (for example the whole log message from the server), all email addresses found in the string will be processed.
/** * Mask email address with asterisks to comply GDPR * john.doe@example.com => j******e@e****e.com * @param {string} emailAddress email address * @returns {string} masked email address */ function maskEmailAddress (emailAddress) { function mask(str) { var strLen = str.length; if (strLen > 4) { return str.substr(0, 1) + str.substr(1, strLen - 1).replace(/\w/g, '*') + str.substr(-1,1); } return str.replace(/\w/g, '*'); } return emailAddress.replace(/([\w.]+)@([\w.]+)(\.[\w.]+)/g, function (m, p1, p2, p3) { return mask(p1) + '@' + mask(p2) + p3; }); return emailAddress; } return maskEmailAddress('random string username@example.com test');