Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reformat string containing uk postcode using regex

How can I format a string using Javascript to match a regex?

I am using UK postcodes which could match any of the following

N1 3LD
EC1A 3AD
GU34 8RR

I have the following regex which validates a string correctly, but I am unsure how to use the regex as a mask to format EC1A3AD to EC1A 3AD / GU348RR to GU34 8RR / N13LD to N1 3LD.

My regex is /^[A-Za-z]{1,2}[0-9A-Za-z]{1,2}[ ]?[0-9]{0,1}[A-Za-z]{2}$/

Thank you

like image 412
Paul Chops Helyer Avatar asked May 22 '12 11:05

Paul Chops Helyer


People also ask

What is the format of UK postcode?

It consists of a numeric character followed by two alphabetic characters. The numeric character identifies the sector within the postal district. The alphabetic characters then define one or more properties within the sector. For example: PO1 3AX PO refers to the postcode area of Portsmouth.

How do you type a postcode?

Postcodes should always be in BLOCK CAPITALS as the last line of an address. Do not underline the postcode or use any punctuation. Leave a clear space of one character between the two parts of the postcode and do not join the characters in any way.

What is a postcode format?

The basic format consists of five numerical digits. The system of ZIP+4 code, introduced in the 1983, added four digits to the end of old five-digit codes. The new system of postcodes helps to determine a more precise location than the old one.

How do British postal codes work?

Each postcode consists of two parts. The first part is the outward postcode, or outcode. This is separated by a single space from the second part, which is the inward postcode, or incode. The outward postcode enables mail to be sent to the correct local area for delivery.


1 Answers

If you use the regular expression /^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(\d[A-Z]{2})$/ you can extract the two parts of the postcode and reassemble them with an intervening space.

var list = ['N13LD', 'EC1A3AD', 'GU348RR'];

for (var i = 0; i < list.length; i++) {
  var parts = list[i].match(/^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(\d[A-Z]{2})$/);
  parts.shift();
  alert(parts.join(' '));
}

output

N1 3LD
EC1A 3AD
GU34 8RR
like image 169
Borodin Avatar answered Oct 26 '22 11:10

Borodin