hide all `numbers` except last 4 using js regex

I’m struggling to find the proper regex to replace my phone number string. The goal is to mask all numbers except the last 4.

I have /d(?=d{4})/g, "*" but it wont work with other symbols such as ( and -

For example

'1234567890'.replace(/d(?=d{4})/g, "*"); -> ******7890 (works)

'(123)456-7890'.replace(/d(?=d{4})/g, "*"); -> (123)456-7890 (doesn’t work, I want (***)***-7890 here)

So I want to be able to ignore all symbols except numbers, any ideas? Thanks!

Answer

Use

/d(?=(?:D*d){4})/g

See proof.

EXPLANATION

--------------------------------------------------------------------------------
  d                       digits (0-9)
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    (?:                      group, but do not capture (4 times):
--------------------------------------------------------------------------------
      D*                      non-digits (all but 0-9) (0 or more
                               times (matching the most amount
                               possible))
--------------------------------------------------------------------------------
      d                       digits (0-9)
--------------------------------------------------------------------------------
    ){4}                     end of grouping
--------------------------------------------------------------------------------
  )                        end of look-ahead

See code example:

const strings = ["(123)456-7890", "1234567890"]
strings.forEach( phone_number =>
  console.log(phone_number.replace(/d(?=(?:D*d){4})/g, "*"))
)

Leave a Reply

Your email address will not be published. Required fields are marked *