最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Formatting Canadian postal codes with .splice() - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Feb 24, 2014 at 22:21 JDillon522JDillon522 19.7k15 gold badges50 silver badges82 bronze badges
Add a ment  | 

1 Answer 1

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

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

发布评论

评论列表(0)

  1. 暂无评论