Reputation: 113
How can I partially hide email address like this in Javascript?
[email protected] => ex**pl**ai*@domain.com
I have modify the below code, but can get the result that I need, it's just return this result:
exam*******@domain.com
email.replace(/(.{4})(.*)(?=@)/, function (gp1, gp2, gp3) {
for (let i = 0; i < gp3.length; i++) {
gp2 += "*";
}
return gp2;
});
Upvotes: 4
Views: 3572
Reputation: 1275
If you want to only replace the digits close to the @ and allow it to add * base on the length, you can do this
const separatorIndex = email.indexOf('@');
if (separatorIndex < 3)
return email.slice(0, separatorIndex).replace(/./g, '*')
+ email.slice(separatorIndex);
const start = separatorIndex - Math.round(Math.sqrt(separatorIndex)) - 1;
const masked = email.slice(start, separatorIndex).replace(/./g, '*');
return email.slice(0, start) + masked + email.slice(separatorIndex);
Upvotes: 0
Reputation: 163457
As a regex for the accepted answer, I would suggest making sure to match only a single @ sign by making use of a negated character class [^\s@]
matching any char except a whitespace char or an @ itself.
This way you might also use it for multiple email addresses, because using (?=.*@)
with multiple @ signs can give unexpected results.
([^\s@]{2})([^\s@]{1,2})(?=[^\s@]*@)
In the pattern that you tried, you matched 4 times any char using (.{4})
. Repeating 4 chars might be done using a positive lookbehind. Then you could get the match only without groups.
First assert a whitespace boundary to the left. Then start with an offset of 2 chars, optionally repeated by 4 chars.
Then match 1 or 2 chars, asserting an @ to the right.
const partialMask = s => s.replace(
/(?<=(?<!\S)[^\s@]{2}(?:[^\s@]{4})*)[^\s@]{1,2}(?=[^\s@]*@)/g,
m => '*'.repeat(m.length)
);
console.log(partialMask("[email protected]"));
Upvotes: 0
Reputation: 4691
Simply do this
function maskFunc(x) {
var res = x.replace(/(..)(.{1,2})(?=.*@)/g,
(beforeAt, part1, part2) => part1 + '*'.repeat(part2.length)
);
return res
}
console.log(maskFunc('[email protected]'));
Upvotes: 0
Reputation: 21
This would be one way to solve your problem:
function f(mail) {
let parts = mail.split("@");
let firstPart = parts[0];
let encrypt = firstPart.split("");
let skip = 2;
for (let i = 0; i < encrypt.length; i += 1) {
if (skip > 0) {
skip--;
continue;
}
if (skip === 0) {
encrypt[i] = "*";
encrypt[i + 1] = "*";
skip = 2;
i++;
}
}
let encryptedMail = `${encrypt.join("")}@${parts.slice(1)}`;
return encryptedMail;
}
Upvotes: 0
Reputation: 386680
You could seach for a group of four characters and replace a group of two until you found an @
sign-
const
mask = string => string.replace(
/(..)(.{1,2})(?=.*@)/g,
(_, a, b) => a + '*'.repeat(b.length)
);
console.log(mask('[email protected]'));
Upvotes: 7