Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting Canadian postal codes with .splice()

Tags:

javascript

I need to properly format a Canadian zip code if its entered in wrong.

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

I've tried this: (its broken up for testing purposes)

  shipping.zip = shipping.zip.toUpperCase().split('')

  shipping.zip = shipping.zip.splice(3, 0, ' ')

  shipping.zip = shipping.zip.join().replace(/,/g, '');

But when I enter in :

m5r2g3

I Get this:

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

[ ]

And thats it. I have no idea why its not working. Please help. Thanks.

like image 384
JDillon522 Avatar asked Feb 24 '14 22:02

JDillon522


People also ask

How do you format a Canadian postal code?

Like British, Irish and Dutch postcodes, Canada's postal codes are alphanumeric. They are in the format A1A 1A1, where A is a letter and 1 is a digit, with a space separating the third and fourth characters.

How do I format a Canadian zip code in Excel?

Select the cell or range of cells that you want to format. , click Custom. In the Format Cells dialog box, under Category, click Custom. In the Type box, type *0 followed by the postal code format that you want to use.

What is the proper format for a postal code?

The most complete ZIP Code is a nine-digit number consisting of five digits, a hyphen, and four digits, which the USPS describes by its trademark ZIP+4. The correct format for a numeric ZIP+4 code is five digits, a hyphen, and four digits.

Is space required in Canada postal code?

Canadian postal codes are usually written with a space, and the module should not fail a postal code for validation because it does (or does not) have a space between the two three-character groups. Patch follows shortly.


1 Answers

'm5r2g3'.toUpperCase().replace(/\W/g,'').replace(/(...)/,'$1 ') // "M5R 2G3"

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

like image 153
Matt Avatar answered Sep 30 '22 18:09

Matt