Reformat string containing uk postcode using regex
javascript, regex
Solution
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
Problem
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