5

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!

2
  • This is the best I could get: "[email protected]".replace(/(.{2})(.*)(?=@)/, '$1*'). Commented Sep 3, 2018 at 17:48
  • Why are you doing this with JavaScript? The email addresses are actually already in the client's browser. So, this is only for display purposes. It's not safe to use it to actually prevent the user to see the email addresses.
    – ssc-hrep3
    Commented Sep 4, 2018 at 18:12

5 Answers 5

15

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.

9

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>

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

1
  • OP wants to keep only two characters at the beggining, and not to hide the last three.. Commented Sep 3, 2018 at 17:49
3

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

Demo

-1

I found a solution in flutter of dart

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.