Canadian Postal Code in JS
Match Canadian postal codes in the A1A 1A1 or A1A1A1 format with valid first-letter prefixes.
Try it in the JS tester →Pattern
regexJS
[ABCEGHJ-NPRSTVXY]\d[A-Z] ?\d[A-Z]\d (flags: gi)JavaScript / ECMAScript code
jsJavaScript
const re = new RegExp("[ABCEGHJ-NPRSTVXY]\\d[A-Z] ?\\d[A-Z]\\d", "gi");
const input = "K1A 0B1";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
How the pattern works
The leading character is constrained to letters actually used by Canada Post (D, F, I, O, Q, U, W, Z are excluded). Alternating letter-digit pattern, with an optional space separator.
Examples
Input
K1A 0B1Matches
K1A 0B1
Input
M5V3L9Matches
M5V3L9
Input
12345No match
—