'Partially hide email address with RegEx and Javascript

I'm trying to using RegEx to hide email addresses, except for the first two characters and the email domain.

The function, in that case, is replacing the characters that I want to keep.

email.replace(/^[A-Za-z]{2}/, "**" ).replace(/@[^:]*/, "**" )

What I get: [email protected] > **ail** Expected: em***@domain.com

Anyone here who knows how can I change my RegEx to get the expected result?

Thanks!



Solution 1:[1]

I could only achieve that with a function in the replace. Not sure if that can be achieved with only regex tho. Check it out:

let hideEmail = function(email) {
  return email.replace(/(.{2})(.*)(?=@)/,
    function(gp1, gp2, gp3) { 
      for(let i = 0; i < gp3.length; i++) { 
        gp2+= "*"; 
      } return gp2; 
    });
};

document.querySelector("button").addEventListener("click", function() {
  let emailField = document.querySelector("input");
      
  console.log(hideEmail(emailField.value));
});
<input type="email" value="[email protected]">
<button>Hide e-mail</button>

Solution 2:[2]

This worked perfectly for me:

const email = "[email protected]"
const partialEmail = email.replace(/(\w{3})[\w.-]+@([\w.]+\w)/, "$1***@$2")
console.log(partialEmail)

It captures first 3 characters (just replace the number as per your needs) in 1st group and the domain in 2nd.

Solution 3:[3]

You could try this, show first two characters and the rest always *** in the user part:

var email = "[email protected]";

let hide = email.split("@")[0].length - 2;//<-- number of characters to hide

var r = new RegExp(".{"+hide+"}@", "g")

email = email.replace(r, "***@" );

console.log(email)

I don't know if the three * is a requirement, but I think is a good idea, because you hide the real length.

Solution 4:[4]

You can also have this,(?<=^[A-Za-z0-9]{2}).*?(?=@)

Demo

Solution 5:[5]

I found a solution in flutter of dart

"[email protected]".replaceRange(
                                  0,
                                  "[email protected]"
                                          .indexOf("@") -
                                      3,
                                  "****")

It will show result like that- ****[email protected]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pedro Luz
Solution 2 Dharmaraj
Solution 3
Solution 4 Nambi_0915
Solution 5 Abir Ahsan