Quantcast
Channel: Reformat string containing uk postcode using regex - Stack Overflow
Viewing all articles
Browse latest Browse all 5

Answer by zwirbeltier for Reformat string containing uk postcode using regex

$
0
0

Here is a very simple auto-formatter written in more modern JS that also works as-you-type. It does three things:

  1. It always turns lower-case letters into uppercase
  2. As soon as the postcode allows it reformats spaces
  3. 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}

Viewing all articles
Browse latest Browse all 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>