File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -19,6 +19,11 @@ export const OUTCODE_REGEX = /^[a-z]{1,2}\d[a-z\d]?$/i;
1919 */
2020export const POSTCODE_REGEX = / ^ [ a - z ] { 1 , 2 } \d [ a - z \d ] ? \s * \d [ a - z ] { 2 } $ / i;
2121
22+ /**
23+ * Test for a valid postcode embedded in text
24+ */
25+ export const POSTCODE_CORPUS_REGEX = / [ a - z ] { 1 , 2 } \d [ a - z \d ] ? \s * \d [ a - z ] { 2 } / gi;
26+
2227/**
2328 * Tests for the area section of a postcode
2429 */
@@ -283,3 +288,11 @@ export const parse = (postcode: string): ValidPostcode | InvalidPostcode => {
283288 unit : toUnit ( postcode ) as string ,
284289 } ;
285290} ;
291+
292+ /**
293+ * Searches a body of text for postcode matches
294+ *
295+ * Returns an empty array if no match
296+ */
297+ export const match = ( corpus : string ) : string [ ] =>
298+ corpus . match ( POSTCODE_CORPUS_REGEX ) || [ ] ;
Original file line number Diff line number Diff line change @@ -2,6 +2,8 @@ import { assert } from "chai";
22import * as Postcode from "../lib/index" ;
33import { loadFixtures , TestMethod } from "./util/helper" ;
44
5+ const { match } = Postcode ;
6+
57const testMethod : TestMethod = ( options ) => {
68 const { tests, method } = options ;
79 tests . forEach ( ( { base, expected } ) => {
@@ -123,3 +125,15 @@ describe("Unit parsing", () => {
123125 assert . isNull ( Postcode . parse ( "Definitely bogus" ) . unit ) ;
124126 } ) ;
125127} ) ;
128+
129+ describe ( "match" , ( ) => {
130+ it ( "returns matching postcodes" , ( ) => {
131+ const corpus = `SW1A2Aa is the residence of the Prime Minister. SW1a 2AB is the residence of her no.2. SW1A 1AA is where the queen lives. They are located in the SW1A outcode` ;
132+ assert . deepEqual ( match ( corpus ) , [ "SW1A2Aa" , "SW1a 2AB" , "SW1A 1AA" ] ) ;
133+ } ) ;
134+
135+ it ( "returns an empty array if no match" , ( ) => {
136+ const corpus = `SW1 NW1 E1 E2` ;
137+ assert . deepEqual ( match ( corpus ) , [ ] ) ;
138+ } ) ;
139+ } ) ;
You can’t perform that action at this time.
0 commit comments