Dimitar Christoff
Dimitar Christoff

Reputation: 26165

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.

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:

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.

Upvotes: 0

Views: 4345

Answers (2)

nnnnnn
nnnnnn

Reputation: 150020

I'm not familiar with UK postcodes, but you seem to be saying that having already removed the other parts of the address you've narrowed the address down to:

[Some words] [several-character code] [optional three-character code]

And you want the two-character code. If that is correct then maybe a regex something like this:

/\s([^\s]{2,4})(?:\s...)?$/

Then the bit you want will be returned by .match():

var addressPart = "Greater London W5 1BX",

alert(addressPart.match(/\s([^\s]{2,4})(?:\s...)?$/)[1]); // "W5"

(Of course you can actually test the return from .match() to be sure it worked, but if it worked the bit you want will be the second element of the match array.)

Dodgy demo: http://jsfiddle.net/HjD7w/1/

EDIT: I suspect this won't quite work because the last word of the city name might be mistaken for the first part of the postcode in some cases, but if there are fixed rules about how the alpha and digit characters fit in the postcode you could fix it. (I don't know the rules though.)

Upvotes: 1

Osman Turan
Osman Turan

Reputation: 1371

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.

Upvotes: 2

Related Questions