make a reg ex to test for 4 digit credit card expiry in javascript

The regular expression for 4 digit credit card expiry in Javascript can be written as follows:

index.tsx
const regex = /^(0[1-9]|1[0-2])\/([2-9][0-9])$/;
49 chars
2 lines

This regex pattern matches a 2-digit month (01-12) followed by a forward slash "/", followed by a 2-digit year (20-99). Note that the regex does not check for expiration dates in the past - this is best done outside of the regex.

To test if a string matches this regex pattern, you can use the test() method of the regex object:

index.tsx
const expiry = '12/25';
const regex = /^(0[1-9]|1[0-2])\/([2-9][0-9])$/;

if (regex.test(expiry)) {
  console.log('Valid expiry date');
} else {
  console.log('Invalid expiry date');
}
185 chars
9 lines

In the above example, the test() method returns true because the expiry string matches the regex pattern.

gistlibby LogSnag