简体   繁体   English

如何使用angular5在地址中仅获取邮政编码

[英]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. 这非常适合REGEX。 Here's your regex 这是您的正则表达式

[0-9]{6,6}

This will match all 6 digit sequences. 这将匹配所有6位数字序列。 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. 不过,在那种情况下,您会知道总是需要第二组,因为地址号码始终位于邮政编码之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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