Trying to develop masking for email address using reg expression but not able to achieve the desired result.
Input : harrypotter@howarts.com
After masking I am looking for result something like this:
Output: "ha*****er@how*****.com"
What I tried is this reg expression:
(?<=.)[^@n](?=[^@n]*?[^@n]@)|(?:(?<=@.)|(?!^)G(?=[^@n]*$)).(?=.*.) h*********r@h******.com
Advertisement
Answer
Your question needs some clarification. Here is an answer making some assumptions:
- keep 2 leading and trailing chars of the name part (before
@
) - keep 3 leading chars of the domain part (after
@
) until.
and TLD (top level domain) - replace with three asterisks
***
to more effectively obscure the address (better than exact number of chars replaced) - no replacement for short names and domains.
Code with examples:
[ `harrypotter@hogwarts.com`, `harry@hogwarts.com`, `tim@hogwarts.com`, `harrypotter@cia.gov` ].forEach(str => { let result = str .replace(/^(..).+?(?=..@)/, '$1***') .replace(/(@...).+?(?=.w+$)/, '$1***'); console.log(str + ' => ' + result); });
Output:
harrypotter@hogwarts.com => ha***er@hog***.com harry@hogwarts.com => ha***ry@hog***.com tim@hogwarts.com => tim@hog***.com harrypotter@cia.gov => ha***er@cia.gov
Notice that there are two .replace()
because one or the other replacement may fail if too short. If you combine into one the whole regex would fail if one side fails.
Explanation of first regex:
^
— anchor at start of string(..)
— capture group 1 for two chars.+?
— non-greedy scan for 1+ chars(?=..@)
— positive lookahead for two chars and@
Notice that we could replace the capture group 1 with a positive lookbehind. This is however not supported by all browsers, notably Safari, hence better to void.