I read a bit in this article, but I am not sure why I am failing:
Output.replaceAll("(?<=\s)(?!<).*(?=@)", "xxxx")
As an example, this will be the sample text:
To: <username@gmail.com>
I sent an e-mail to username@gmail.com yesterday
Here, what I want to achieve is replace username in username@gmail.com to "xxxx".
I already have a regex for replacing username in <username@gmail.com>, which works like a charm:
Output.replaceAll("(?<=<).*(?=@)", "xxxx")
Any idea what I am doing wrong?
By the way, I am replacing with hardcoded "xxxx" because I do not understand how to replace with certain amounts of "x" based on the length of the matched result. For example, "username" is 8 characters, so I want to replace it with "x" 8 times ("xxxxxxxx"). Any idea what I should be looking at to learn that? I googled a few times but never found any articles, so I guess I just do not know the right terminology.
Note that \G is not supported by Javascript.
You can match 1+ chars other than not allowed characters and then match the @ and then in the replacement repeat the x char and subtract 1 from the length.
[^\s@<>]+@
See a regex demo.
const regex = /[^\s@<>]+@/g;
const str = `To: <@gmail.com>
I sent an e-mail to a@gmail.com yesterday
To: <aa@gmail.com>
I sent an e-mail to aaa@gmail.com yesterday`;
console.log(str.replace(regex, m => `${'x'.repeat(m.length - 1)}@`));
You can replace .* in your regex with [^\s]+.
As for replacing with xxx, replaceAll function can accept a function as a replacer:
console.log(
"I sent an e-mail to username@gmail.com yesterday".replaceAll(
/(?<=\s)(?!<)[^\s]+(?=@)/g,
(...match) => {
let username = match[0]
let replacer = ""
for (let i = 0; i < username.length; i++){
replacer += "x"
}
return replacer
})
)
You can read about it here