Skip to content

Instantly share code, notes, and snippets.

@iki
Last active July 31, 2022 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iki/18b2577d6a41b790cf9a92e23f397a43 to your computer and use it in GitHub Desktop.
Save iki/18b2577d6a41b790cf9a92e23f397a43 to your computer and use it in GitHub Desktop.
const hide = (s: string) => '*'.repeat(s.length);
const hideEachSecondMatch = (_match: string, ...matches: string[]) =>
matches
.slice(0, -2)
.map((m, i) => (i % 2 ? hide(m) : m))
.join('');
// Hide all characters in email name, except first and last character
// FIXME: Better hide at least one character for 1-2 character names
const hideEmail = (email: string, options?: { domain?: boolean }) =>
email.replace(
options?.domain ? /^(.?)(.*)(.@.)(.*)(\.[^.]+)$/ : /^(.)(.*)(.@.+)/,
hideEachSecondMatch
);
hideEmail('e@oakslab.com', { domain: true }); // 'e@o******.com'
hideEmail('em@oakslab.com', { domain: true }); // 'em@o******.com'
hideEmail('ema@oakslab.com', { domain: true }); // 'e*a@o******.com'
hideEmail('email@oakslab.com', { domain: true }); // 'e***l@o******.com'
hideEmail('email@oakslab.com'); // 'e***l@example.com'
@Ketcap
Copy link

Ketcap commented Jul 31, 2022

No words, great solution regexp beast ❤️

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