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.
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