Skip to content

Instantly share code, notes, and snippets.

@thewarpaint
Last active April 12, 2020 02:53
Show Gist options
  • Save thewarpaint/7b78cc303cd9e20a53a8d2f8399671f6 to your computer and use it in GitHub Desktop.
Save thewarpaint/7b78cc303cd9e20a53a8d2f8399671f6 to your computer and use it in GitHub Desktop.
Mask an email address
function maskEmailAddress (emailAddress = '') {
const [
username = '',
domainName = ''
] = emailAddress.split('@')
return username.substring(0, 2) +
'***@' +
domainName
.split('.')
.map(domainNamePart => domainNamePart.substring(0, 1) + '**')
.join('.')
}
console.assert(maskEmailAddress('julian.casablancas@merch.strokes.com') === 'ju***@m**.s**.c**')
console.assert(maskEmailAddress('julian.casablancas@strokes.com') === 'ju***@s**.c**')
console.assert(maskEmailAddress('julian.casablancas@localhost') === 'ju***@l**')
console.assert(maskEmailAddress('') === '***@**')
console.assert(maskEmailAddress() === '***@**')
@ElHacker
Copy link

ElHacker commented Apr 12, 2020

I went with the regex approach, might still be able to be simplified.

function replacer(match, username, domain) {
  username = username.replace(/(\w{2}).*/,'$1**@');
  let domainParts = domain.replace(/(.)\w*(\.?)/g, '$1**$2');
  return username + domainParts;
}

function maskEmailAddress(email) {
  if (!email) {
    return "***@***";
  }
  return email.replace(/(.*)@(.*)/, replacer);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment