Home > Blockchain >  What will be the best regex Expression for censoring email?
What will be the best regex Expression for censoring email?

Time:02-20

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 : [email protected]

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

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

const email = [email protected];
const regex = /(?<!^).(?!$)/g;
const censoredEmail = email.replace(regex, '*');

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

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

CodePudding user response:

You can use

const email = '[email protected]';
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 *.

  • Related