Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to replace characters between strings

Tags:

regex

Suppose I have an email address, '[email protected]'. I want to replace all the characters between 'a' and 'f' so the result would look like 'a****[email protected]'.

Trying to do this with a regex and replace

str.replace(/^(.*?)@/gi, '*');

But the results look like this

*gmail.com

Is there a way to do what I need?

like image 795
Geuis Avatar asked Jun 30 '26 23:06

Geuis


1 Answers

This is not an answer to your actual question, but I'd like to challenge you that your idea is not a good one. It's best not to show how long an email address is by replacing the internal letters with the same number of *s. It's better to use a fixed number of *s.

You seem to be using javascript, which doesn't have lookbehind assertions, and capturing in this case may be simpler to understand too, so I'd do this to replace with a constant number of *s

str.replace(/^(.).*(.@)/, '$1***$2')
like image 90
smathy Avatar answered Jul 03 '26 04:07

smathy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!