Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript REGEX to find credit card number in string and mask

I want to search a string and mask the a credit card for security.

"Hi here is my card number its visa 4242 4242 4242 4242"
"Hi here is my card number its visa 4242424242424242"
"Hi here is my card number its visa 4242-4242-4242-4242"

Should be converted to:

"Hi here is my card number its visa **** **** **** 4242"

I need to do this on the client in Javascript. I know there are quite a few resources and questions on the web and SO.

I have found two regex, but both throw errors: "Uncaught SyntaxError: Invalid or unexpected token"

"Hi here is my card number its visa 4242 4242 4242 4242".match("(\d{4}-?){4}")

and

"Hi here is my card number its visa 4242 4242 4242 4242".match(\b4\d{3}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}[ -]\b)

I think the expressions are not compatible with JS?

I also understand they will return the string, I would then convert the string (mask it) and then use a simple replace on the original string.

Can anybody help me with the regex part of this problem?

like image 930
MartinWebb Avatar asked Dec 19 '22 01:12

MartinWebb


1 Answers

See regex in use here

\b(?:\d{4}[ -]?){3}(?=\d{4}\b)
  • \b Assert position as a word boundary. You can remove this if you want to catch cases such as My visa is1234567812345678
  • (?:\d{4}[ -]?){3} Match the following exactly 3 times
    • \d{4} Match any digit 4 times
    • [ -]? Optionally match a space or hyphen
  • (?=\d{4}\b) Positive lookahead ensuring what follows is 4 digits (and ensuring what follows it is not a word character). Similar to my first point, catching cards numbers that are followed by words such as My visa is 1234567812345678please use it carefully, use (?=\d{4}(?!\d)) instead.

const r = /\b(?:\d{4}[ -]?){3}(?=\d{4}\b)/gm
const a = [
  "Hi here is my card number its visa 4242 4242 4242 4242",
  "Hi here is my card number its visa 4242424242424242",
  "Hi here is my card number its visa 4242-4242-4242-4242"
]
const subst = `**** **** **** `

a.forEach(function(s) {
  console.log(s.replace(r, subst))
})
like image 60
ctwheels Avatar answered May 24 '23 20:05

ctwheels