'What will be the best regex Expression for censoring email?
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 : [email protected]
Required : e***********@e******.com
Help me getting this in javascript, Current code I am using to censor :
const email = [email protected];
const regex = /(?<!^).(?!$)/g;
const censoredEmail = email.replace(regex, '*');
Output: e**********************m
Please help me getting e***********@e******.com
Solution 1:[1]
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 string
In the replacement use all 5 capture groups, where you replace group 2 and 4 with *.
const regex = /^([^\s@])([^\s@]*)@([^\s@])([^\s@]*)(\.[^\s.@]+)$/;
[
"[email protected]",
"test"
].forEach(email =>
console.log(
email.replace(regex, (_, g1, g2, g3, g4, g5) =>
`${g1}${"*".repeat(g2.length)}@${g3}${"*".repeat(g4.length)}${g5}`)
)
);
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 | The fourth bird |
