Regex replace phone numbers with asterisks pattern

I want to apply a mask to my phone numbers replacing some characters with "*".

The specification is the next:

Phone entry: (123) 123-1234

Output: (1**) ***-**34

I was trying with this pattern: "\B\d(?=(?:\D*\d){2})" and the replacing the matches with a "*"

But the final input is something like (123)465-7891 -> (1**)4**-7*91

Pretty similar than I want but with two extra matches. I was thinking to find a way to use the match zero or once option (??) but not sure how.

Upvotes: 4

Views: 2627

Answers (3)

Jerahmeel Anibor
Jerahmeel Anibor

Reputation: 37

Some "quickie":

function maskNumber(number){
    var getNumLength = number.length;
    // The number of asterisk, when added to 4 should correspond to length of the number
    var asteriskLength = getNumLength - 4;
    var maskNumber = number.substr(-4); 
    for (var i = 0; i < asteriskLength; i++) maskNumber+= '*';

    var mask = maskNumber.split(''), maskLength = mask.length;
    for(var i = maskLength - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var tmp = mask[i];
        mask[i] = mask[j];
        mask[j] = tmp;
    }

    return mask.join('');
}

Upvotes: 0

Aaron
Aaron

Reputation: 24812

Alternative without lookarounds :

  • match \((\d)\d{2}\)\s+\d{3}-\d{2}(\d{2})
  • replace by (\1**) ***-**\2

In my opinion you should avoid lookarounds when possible. I find them less readable, they are less portable and often less performant.

Testing Gurman's regex and mine on regex101's php engine, mine completes in 14 steps while Gurman's completes in 80 steps

Upvotes: 3

Gurmanjot Singh
Gurmanjot Singh

Reputation: 10360

Try this Regex:

(?<!\()\d(?!\d?$)

Replace each match with *

Click for Demo

Explanation:

  • (?<!\() - negative lookbehind to find the position which is not immediately preceded by (
  • \d - matches a digit
  • (?!$) - negative lookahead to find the position not immediately followed by an optional digit followed by end of the line

Upvotes: 5

Related Questions