简体   繁体   中英

How to get only zipcode in address using angular5

I have an address like this

address = "1a, Hitech City Rd, Sri Sai Nagar, Madhapur, Hyderabad, Telangana 500081, India"

Here i need only zipcode, I tried like this

ngOnInit(){
var y=this.address.split(",")
this.z=y[5]
this.addr=this.z.split(" ")[2]
}

and this is working, but address is not exactly same to all locations. I modified like this

address = "1a, Hitech City Rd, Sri Sai Nagar, Madhapur, Hyderabad,500081, India,Streetno:123" 

in the above address then the above logic will not work. Is there any other way to get only zipcode. Please help.

Try this: you can place pin/zip code anywhere in the text.

 let address = "1a, Hitech City Rd, Sri Sai Nagar,500081, Madhapur, Hyderabad, Telangana, India";

 let res = address.split(",").map(data => data
  .trim()
  .match("\\d{6}"))
  .filter(filtered => filtered)[0][0];

 console.log(res);

Hope this would help you! :)

Zip codes are always the same length, format, and are always numeric. This is a perfect fit for a REGEX. Here's your regex

[0-9]{6,6}

This will match all 6 digit sequences. You will need to handle the edge case of having an address number which is six digits. In that case, though, you know you'll always want the second set since address numbers will always come before the zip code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM