Hello I am stuck on a problem for censoring email in a specific format, but I am not getting how to do that, please help me!
Email : exampleEmail@example.com
Required : e***********@e******.com
Help me getting this in javascript, Current code I am using to censor :
const email = exampleEmail@example.com;
const regex = /(?<!^).(?!$)/g;
const censoredEmail = email.replace(regex, '*');
Output: e**********************m
Please help me getting e***********@e******.com
You can use
const email = 'exampleEmail@example.com';
const regex = /(^.|@[^@](?=[^@]*$)|\.[^.]+$)|./g;
const censoredEmail = email.replace(regex, (x, y) => y || '*');
console.log(censoredEmail );
// => e***********@e******.com
Details:
( - start of Group 1:
^.| - start of string and any one char, or@[^@](?=[^@]*$)| - a @ and any one char other than @ that are followed with any chars other than @ till end of string, or\.[^.]+$ - a . and then any one or more chars other than . till end of string) - end of group| - or. - any one char.The (x, y) => y || '*' replacement means the matches are replaced with Group 1 value if it matched (participated in the match) or with *.
If there should be a single @ present in the string, you can capture all the parts of the string and do the replacement on the specific groups.
^ Start of string([^\s@]) Capture the first char other than a whitespace char or @ that should be unmodified([^\s@]*) Capture optional repetitions of the same@ Match literally([^\s@]) Capture the first char other than a whitespace char or @ after it that should be unmodified([^\s@]*) Capture optional repetitions of the same(\.[^\s.@]+) Capture a dot and 1+ other chars than a dot, @ or whitespace char that should be unmodified$ End of stringIn the replacement use all 5 capture groups, where you replace group 2 and 4 with *.
const regex = /^([^\s@])([^\s@]*)@([^\s@])([^\s@]*)(\.[^\s.@]+)$/;
[
"exampleEmail@example.com",
"test"
].forEach(email =>
console.log(
email.replace(regex, (_, g1, g2, g3, g4, g5) =>
`${g1}${"*".repeat(g2.length)}@${g3}${"*".repeat(g4.length)}${g5}`)
)
);