Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to mark first character?

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading