UNPKG

vladdress

Version:

Lightweight Street Address Parser Written in TypeScript

68 lines (67 loc) 2.03 kB
"use strict"; exports.__esModule = true; exports.parseZipCode = void 0; /** * Parses ZIP/Postal Codes in these forms: * * - `#####` (US ZIP Code - 5 Digit) * - `#####-####` (US ZIP Code - 5 + 4 Digit) * - `A1A-1A1`/`A1A1A1`/`"A1A 1A1"` (Canadian Zip Code) * * The input to this function should **end** with the ZIP code to process. * Other cases are not yet supported. For example: * @example * * parseZipCode('1 Main Street, San Diego CA 92115') * * @param input * @returns */ function parseZipCode(input) { input = input === null || input === void 0 ? void 0 : input.trim(); if (!input) { return undefined; } var match = input.match(/(?<zip5>\d{5})-?(?:(?<zip4>\d{4}))?$/); if (match && !(match === null || match === void 0 ? void 0 : match.groups)) { return { originalInput: input, trimmedString: input.trim() }; } var _a = (match === null || match === void 0 ? void 0 : match.groups) || {}, zip4 = _a.zip4, zip5 = _a.zip5; // let zipInternational: string | undefined; if (!zip5) { var match_1 = input.match(/[A-Z]\d[A-Z][\s-]?\d[A-Z]\d/); if (!match_1) { return { originalInput: input, trimmedString: input.trim() }; } var fullMatch = match_1[0]; if (!fullMatch) { return { originalInput: input, trimmedString: input.trim() }; } return { zipInternational: fullMatch, originalInput: input, trimmedString: input .replace(fullMatch, '') .trim() }; } var totalMatchLength = (match === null || match === void 0 ? void 0 : match[0].length) || 0; return { zip4: zip4, zip5: zip5, originalInput: input, trimmedString: input .substring(0, input.length - totalMatchLength) .trim() }; } exports.parseZipCode = parseZipCode;