I’m trying to mask email, so if I have this email:
[email protected]
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 = "[email protected]".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!
2
Answers
Replace all word characters except the first one and prefixed with a non word character:
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 oneAlso we have an option manually split and mask:
Which is actually faster than the regex: