JavaScript / ECMAScript

US ZIP Code in JS

Match US ZIP codes in 5-digit (12345) and ZIP+4 (12345-6789) formats.

Try it in the JS tester →

Pattern

regexJS
\b\d{5}(?:[\-\s]\d{4})?\b   (flags: g)

JavaScript / ECMAScript code

jsJavaScript
const re = new RegExp("\\b\\d{5}(?:[\\-\\s]\\d{4})?\\b", "g");
const input = "90210";
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

Core is 5 digits. The optional group (?:[\-\s]\d{4})? adds support for the ZIP+4 extension separated by hyphen or space.

Examples

Input

90210

Matches

  • 90210

Input

10001-1234

Matches

  • 10001-1234

Input

1234

No match

Same pattern, other engines

← Back to US ZIP Code overview (all engines)