find credit card numbers in a string using regex in javascript

To find credit card numbers in a string using regex in JavaScript, you can use the following pattern:

index.tsx
const regex = /(\d{4}[ -]?){3}\d{4}/g;
const str = "My credit card number is 1234-5678-9012-3456";
const matches = str.match(regex);

console.log(matches); // ["1234-5678-9012-3456"]
183 chars
6 lines

This pattern matches a sequence of digits (4 in a row, followed by an optional space or hyphen) three times, followed by another sequence of 4 digits. The g flag at the end of the regex ensures that all matches are found, not just the first one.

In the above example, str.match(regex) returns an array with one element, which is the credit card number found in the string. If there are multiple credit card numbers in the string, they will all be returned in the array.

gistlibby LogSnag