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
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With