I’m trying to mask email, so if I have this email:
harrypotter@gmail.com
after masking it I want to show it like this:
h**********@g****.c**
Basically always show ONLY the first character in the beginning, the first character after @ symbol, and first character after .com (Example: only show letter c)
This is my code:
let myEmail = "harrypotter@gmail.com".replace(/^(.).+?(?=@)/, '$1***').replace(/(@.).+?(?=\.\w+$)/, '$1***')
console.log(myEmail);
Can anyone tell me what I’m missing or if this could be simplified in a better way? Thanks a lot in advance!
>Solution :
Replace all word characters except the first one and prefixed with a non word character:
let myEmail = "harrypotter2@gmail.com".replace(/(?<!(\W|^))\w/g, '*');
console.log(myEmail);
But when the name part contains dots and special characters like often used + we end up with a more complex regex like:
(?<!(^|@))[^@](?!\w+$) – here we replace all characters that aren’t @ except the first one and after @ and before the top level domain
(?<=\w)\w(?=\w+$) – here we replace the characters in the top level domain except the first one
let myEmail = "harry.potter+job@gmail.com".replace(/(?<!(^|@))[^@](?!\w+$)|(?<=\w)\w(?=\w+$)/g, '*');
console.log(myEmail);