Formatting Canada Postcodes with .splice ()

I need to format the Canadian zip code correctly if it is entered incorrectly.

Format: ### ### where "#" can be a number or a letter, for example: M5R 2G3

I tried this: (its broken for testing)

shipping.zip = shipping.zip.toUpperCase().split('') shipping.zip = shipping.zip.splice(3, 0, ' ') shipping.zip = shipping.zip.join().replace(/,/g, ''); 

But when I enter:

m5r2g3

I get the following:

['M', '5', 'R', '2', 'G', '3']

[]

And here it is. I have no idea why it is not working. Please help. Thanks.

+6
source share
1 answer
 'm5r2g3'.toUpperCase().replace(/\W/g,'').replace(/(...)/,'$1 ') // "M5R 2G3" 

replace(/\W/g,'') removes all non-alphanumeric characters (including commas).

+6
source

All Articles