简体   繁体   中英

Extract post code from an address string - JavaScript - UK

I would like to be able to get a postcode from a random string.

Strings I may receive

2 Castlebar Park, London, Greater London W5 1BX, UK
The Ludgrove Club, Alan Drive, Barnet EN5 2PU
The Ludgrove Club, Alan Drive, Barnet EN52PU
The Ludgrove Club, Alan Drive, Barnet E5, UK

These are just examples to demonstrate what they might look like.

What I have so far is:

'The Ludgrove Club, Alan Drive, Barnet EN5 2PU'.match(/^([A-Za-z]{1,2}[0-9A-Za-z]{1,2})[ ]?([0-9]{0,1}[A-Za-z]{2})$/)
//returns null

This works on post codes, but not if they are part of a larger string.

I believe you're looking to match "EN52PU" as well as "EN5 2PU" as well as just "E5". This should do the trick:

/[A-Za-z]{1,2}\d{1,2}(?:\s?(?:\d?\w{2}))?/

See in action with explanations here: https://regex101.com/r/Nbvu58/2

Improving @Paul Armstrong answer a bit, in case of a whole string:

"The Ludgrove Club, Alan Drive, Barnet EN5 2PU".split(",").map(s => s.trim().match(/([A-Za-z]{1,2}\d{1,2})(\s?(\d?\w{2}))?/)).filter(e => e)[0][0]

returns "EN5 2PU"

I would check that the zip code starts from a word break, and that the end of it is delimited by a comma or end-of-string:

/(\b[A-Z]{1,2}\d{1,2}( ?\d?[A-Z]{2})?)(?=,|$)/

 // Sample data [ '2 Castlebar Park, London, Greater London W5 1BX, UK', 'The Ludgrove Club, Alan Drive, Barnet EN5 2PU', 'The Ludgrove Club, Alan Drive, Barnet EN52PU', 'The Ludgrove Club, Alan Drive, Barnet E5, UK' ].forEach(input => { // Iterate over them var m = input.match(/(\\b[AZ]{1,2}\\d{1,2}( ?\\d?[AZ]{2})?)(?=,|$)/); if (m) console.log(m[0]); // Output match }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM