Ad

What Will Be The Best Regex Expression For Censoring Email?

- 1 answer

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

Ad

Answer

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 *.

Ad
source: stackoverflow.com
Ad