Reputation: 419
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!
Upvotes: 5
Views: 17672
Reputation: 3049
I found a solution in flutter of dart
"[email protected]".replaceRange(
0,
"[email protected]"
.indexOf("@") -
3,
"****")
It will show result like that- ****[email protected]
Upvotes: -1
Reputation: 50900
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.
Upvotes: 15
Reputation: 21465
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>
Upvotes: 9
Reputation: 5250
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.
Upvotes: 3