Search code examples
regexdata-masking

Javascript Regex for data masking


I've been trying to figure out how to specifically mask certain parts of the string.

For example, if I were to mask first four letters in an email:

alias12@gmail.com => ****s12@gmail.com

and

mask four numbers before the last four numbers of a phone number:

+15123452345 => +151****2345

What would each of these regex expressions be using replace?


Solution

  • For the first one, just match the start of the string and 4 more .:

    ^.{4}
    

    For the second one, use this:

    .{4}(?=.{4}$)
    

    This matches 4 . until it sees that after it, there are 4 more . followed by the end of string.