Search code examples
javascriptregexregexp-replace

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

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