简体   繁体   中英

Rewrite this regex without using lookbehind - invalid regex with JS

Only minimal experience with Regex, I am trying to implement some email masking in node.js, all was well running it locally but once pushed up to the server I am getting invalid Regex errors.

The Regex code example can be found here

https://regexr.com/42uid

var email = 'foo@bar.com'
const regex = /(.)[^@\n](?=[^@\n]*[^@\n]@)|(?:(@.)|(?!^)\G(?=[^@]*$)).(?!$)/g;
const maskedEmail = email.replace(regex, '*');

maskedEmail should return

  f*o@b*r.com

I have narrowed the issue down to being the 'lookbehind/lookahead' which as I understand it is not available in JS. However I am not aware how best to re-write it.

You can capture it in multiple groups and then retrieve that data in the replace with $1 , $2 , etc.

By using this regex: ^(.).*(.@.).*(.\\.[^\\.]+)$
and using the following replace string: $1*$2*$3
it will result in: f*o@b*r.com

Link to my Fiddle: https://regexr.com/42um8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM