Here is a very simple auto-formatter written in more modern JS that also works as-you-type. It does three things:
- It always turns lower-case letters into uppercase
- As soon as the postcode allows it reformats spaces
- It removes any additional input as soon as there is a valid postcode
For 2. it uses the format examples given by wikipedia https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation
const format = (value) => { value = value.toUpperCase() const splits = [ // See https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation /(.*)([0-9][A-Z]{2})/, // … 9AA[anything else removed] /^([A-Z][0-9])([0-9][A-Z].*)/, // A9 9A… /^([A-Z][0-9]{2})([0-9].*)/, // A99 9… /^([A-Z][0-9][A-Z])(.*)/, // A9A … /^([A-Z]{2}[0-9]{2})([0-9].*)/, // AA99 9… /^([A-Z]{2}[0-9])([0-9][A-Z].*)/, // AA9 9A… /^([A-Z]{2}[0-9][A-Z])(.*)/, // AA9A … ] for (const split of splits) { const parts = value.replace('', '').match(split) if (parts) { return parts.slice(1).join('') } } return value}