Search code examples
javascriptregexpostal-code

regex to extract part of a UK postcode from an address string


I really don't know enough about regex to tackle this on my own so...

I am playing with geolocation API and my goal is to get a rough idea about the whereabouts of the visitor so I can list services on offer in that particular area.

this is done via the leading part of the postcode string. eg n17 9ht, my interest is in n17

that's all fair but I get different outputs in chrome and IE9, firefox is miles better and returns a postalCode string automatically.

  • chrome: 2 Castlebar Park, London, Greater London W5 1BX, UK
  • ie9: 3-6 Mt Ave, London Borough of Ealing, London W5, UK

whereas neither of these is my address, W5 is correct.

the question is, how do I extract just W5 out of the two possible strings i am being given?

Obviously, the string is being split by ,, so I am looking at getting W5 (or any possible uk postcode leading part) from a string looking like:

  • Greater London W5 1BX
  • London W5

it will always have a space between the 2 parts of the post code (if 2-nd is supplied).

I don't care about BFPO / GIR cases so it's pretty much just part 1, which can be as simple as n1 or ec3a - so the way I figure, the logic needs to be:

  1. extract either the full or partial postcode.
  2. take part 1 (or the only part) and pass it on.

any help appreciated.


Solution

  • Here is the one of the longest regular expression which supports all UK postal code syntax according to Wikipedia article (including partials):

    ([A-Z]?\d(:? \d[A-Z]{2})?|[A-Z]\d{2}(:? \d[A-Z]{2})?|[A-Z]{2}\d(:? \d[A-Z]{2})?|[A-Z]{2}\d{2}(:? \d[A-Z]{2})?|[A-Z]\d[A-Z](:? \d[A-Z]{2})?|[A-Z]{2}\d[A-Z](:? \d[A-Z]{2})?),\s*UK$
    

    I didn't test it properly, but at least works for your cases.