find credit card numbers in a string using regex in typescript

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

index.ts
const regex = /\b\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}\b/g;
58 chars
2 lines

This regex searches for sets of 16 digits separated by spaces, hyphens, or a combination of both.

You can then use this regex with a string method such as match() to extract all the matching credit card numbers from the string.

index.ts
const myString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas pharetra aliquet magna, feugiat aliquam odio lacinia vel. Sed rhoncus condimentum erat id hendrerit. Duis ultrices fringilla libero, id congue neque imperdiet id. Nam euismod ipsum quis massa malesuada, ut consectetur odio pharetra. Fusce pulvinar, tellus at blandit consequat, tellus leo lacinia dolor, vitae hendrerit nisi nisi et eros. Ut aliquam orci vel erat maximus aliquet. Maecenas pharetra quam eget lorem interdum dictum. Nam vestibulum, nibh sed feugiat malesuada, enim arcu malesuada justo, sed tincidunt ligula purus non ligula. Morbi id mi non libero imperdiet fringilla ut et urna. Integer vulputate tincidunt ipsum, sit amet elementum magna scelerisque quis. Credit card numbers: 1234-5678-9012-3456, 1111222233334444, 5555 6666 7777 8888, 5555-6666-7777-8888.";

const creditCardNumbers = myString.match(regex);

console.log(creditCardNumbers);
// Output: ["1234-5678-9012-3456", "1111222233334444", "5555 6666 7777 8888", "5555-6666-7777-8888"]
1141 chars
7 lines

This will output an array of all the credit card numbers found in the string.

gistlibby LogSnag