Regular expression to replace inner credit card numbers with X's?


Is it possible to use regex to replace all characters in a card number with an X, except for the left-outer 4-digits and right-outer 4-digits, when the card number varies in length between 15-19 characters?

I’ve been searching but couldn’t find a solution with variable card lengths.

I’m building a sails.js app.

(Note: For those of you with PCI-compliance worries, I’m not storing credit card numbers and it’s not a live application)


use this pattern


and replace w/ X

(?<=            # Look-Behind
  \d            # <digit 0-9>
  {4}           # (repeated {4} times)
)               # End of Look-Behind
\d              # <digit 0-9>
(?=             # Look-Ahead
  \d            # <digit 0-9>
  {4}           # (repeated {4} times)
)               # End of Look-Ahead  

if your engine does not support look-behind use this pattern instead


Note: will only work properly for 9+ digit numbers

Answered By – alpha bravo

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.