Subhadeep Bose
Subhadeep Bose

Reputation: 73

Need to get Zip Code from An Address using Regex in Javascript

I need to extract Zip/Postal Code out of an address in javascript using Regex.

The address that i am passing currently is :

Vittal Mallya Road, KG Halli, Sampangi Rama Nagar, Bangalore, Karnataka 560001, India

The regex that i have formed for getting the Zip Code is :

var Zip=results[0].formatted_address; Zip = Zip.replace( /^\D+/g, '');

The output that i am getting is 560001, India instead of only 560001. Also, i want to ignore any number that may come in the beginning of the address like Door Number/House/Street Number since i am only concerned with Zip Code. Moreover, it should also work in case we pass a UK/USA Address containing the respective Zip Code. Any help in this matter will be highly appreciated.

Upvotes: 1

Views: 4134

Answers (2)

Claytronicon
Claytronicon

Reputation: 1456

I think it makes more sense to match the zip code, rather than match non numeric items and delete them. This pattern will match US zip codes and Canadian postal codes within an address string

(\d{5}([ -]\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1}[ -]\d{1}[A-Z]{1}\d{1}$)

https://regexr.com/455ns

Upvotes: 1

ruslashev
ruslashev

Reputation: 56

Take a look at your regex in action: regexr.com

^\D+

It matches from begining of line (^) any non-digit (\D) char,
Meaning it will start at beginning of line and end at first number, in your case it will match:

Vittal Mallya Road, KG Halli, Sampangi Rama Nagar, Bangalore, Karnataka 

Then you delete this match, leaving 560001, India


You want \d{6} - matches any digit 6 times, or 6 digits.

Then you can extract value with Pattern and Matcher

Upvotes: 3

Related Questions