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

What will be the best regex Expression for censoring email?

Hello I am stuck on a problem for censoring email in a specific format, but I am not getting how to do that, please help me!

Email : exampleEmail@example.com

Required : e***********@e******.com

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

Help me getting this in javascript,
Current code I am using to censor :

const email = exampleEmail@example.com;
const regex = /(?<!^).(?!$)/g;
const censoredEmail = email.replace(regex, '*');

Output: e**********************m

Please help me getting e***********@e******.com

>Solution :

You can use

const email = 'exampleEmail@example.com';
const regex = /(^.|@[^@](?=[^@]*$)|\.[^.]+$)|./g;
const censoredEmail = email.replace(regex, (x, y) => y || '*');
console.log(censoredEmail );
// => e***********@e******.com

Details:

  • ( – start of Group 1:
    • ^.| – start of string and any one char, or
    • @[^@](?=[^@]*$)| – a @ and any one char other than @ that are followed with any chars other than @ till end of string, or
    • \.[^.]+$ – a . and then any one or more chars other than . till end of string
  • ) – end of group
  • | – or
  • . – any one char.

The (x, y) => y || '*' replacement means the matches are replaced with Group 1 value if it matched (participated in the match) or with *.

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