JavaScript / ECMAScript

UK Postcode in JS

Match UK postcodes in the common outward + inward format (e.g. SW1A 1AA, EC1V 9LB).

Try it in the JS tester →

Pattern

regexJS
[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}   (flags: gi)

JavaScript / ECMAScript code

jsJavaScript
const re = new RegExp("[A-Z]{1,2}\\d[A-Z\\d]? ?\\d[A-Z]{2}", "gi");
const input = "SW1A 1AA";
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

1–2 letters, 1 digit, optional letter/digit, optional space, 1 digit, 2 letters. Case-insensitive flag handles lower and mixed case input.

Examples

Input

SW1A 1AA

Matches

  • SW1A 1AA

Input

EC1V 9LB

Matches

  • EC1V 9LB

Input

B33 8TH

Matches

  • B33 8TH

Same pattern, other engines

← Back to UK Postcode overview (all engines)