skip to Main Content

I’m trying to mask email, so if I have this email:

[email protected]

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)

This is my code:

let myEmail = "[email protected]".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!

2

Answers


  1. '[email protected]'.replace(/^(.).*@(.).*.(.).*$/, '$1***@$2***.$3***')
    
    
    Login or Signup to reply.
  2. Replace all word characters except the first one and prefixed with a non word character:

    let myEmail = "[email protected]".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 = "[email protected]".replace(/(?<!(^|@))[^@](?!w+$)|(?<=w)w(?=w+$)/g, '*');
    console.log(myEmail);

    Also we have an option manually split and mask:

    let myEmail = '[email protected]';
    const [name, domain] = myEmail.split('@');
    
    const hide = str => str[0] + '*'.repeat(str.length - 1);
    
    myEmail = hide(name) + '@' + domain.split('.').map(hide).join('.');
    
    console.log(myEmail);

    Which is actually faster than the regex:

    enter image description here

    <script benchmark data-count="1000000">
    
    const myEmail = '[email protected]';
    
    // @benchmark regex
    
    myEmail.replace(/(?<!(^|@))[^@](?!w+$)|(?<=w)w(?=w+$)/g, '*');
    
    // @benchmark string splitting and padding
    const [name, domain] = myEmail.split('@');
    const hide = str => str[0] + '*'.repeat(str.length - 1);
    hide(name) + '@' + domain.split('.').map(hide).join('.');
    
    </script>
    
    <script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search