简体   繁体   English

从字符串中提取信息-JavaScript

[英]Extract information from string - JavaScript

I am currently implementing google places autocomplete and the module I am using in React Native gives me the address as a whole string and not in address components. 我目前正在实现google place自动补全功能,而我在React Native中使用的模块将我的地址视为一个整体字符串,而不是地址组件。 However, I need to have the postal code and city separate. 但是,我需要将邮政编码和城市分开。 The example response always look like this: 示例响应始终如下所示:

address: 'Calle Gran Vía, 8, 28013 Madrid, Spain

From this string I would need to have an object that looks like this: 从这个字符串中,我需要一个看起来像这样的对象:

{
  city: 'Madrid',
  postal_code: 28013,
}

How could I achieve this? 我怎样才能做到这一点?

It's not the most "clean" or "smooth" answer, but it's something: 这不是最“干净”或“平滑”的答案,但它有以下几点:

 var response = "address: 'Calle Gran Vía, 8, 28013 Madrid, Spain"; var subStr = response.split(",")[2]; var obj = { city: subStr.split(" ")[2], postal_code: subStr.split(" ")[1] }; console.log(obj); 

For the city I think the best way is to use an array of cities and search it in the string 对于城市,我认为最好的方法是使用一系列城市并在字符串中搜索

var str = "Calle Gran Vía, 8, 28013 Madrid, Spain";
var cities = ["Paris", "Berlin", "Madrid"];
var city = cities.filter(function(item) {
  if (str.search(item) != -1)
    return item;
})[0] || null;

For the postal code you should use a regex depending on the country ( a good list of regex by country ) 对于邮政编码,您应该根据国家/地区使用正则表达式( 按国家列出的正则表达式列表

用数组方法用','分隔字符串,取数组的第三个元素,然后用''分隔,然后得到数据点。

If you can always count on it being in that same format, you can do the following. 如果您始终可以指望它采用相同的格式,则可以执行以下操作。

var splitAdress = address.split(",");
//This will give you ["Calle Gran Vía", " 8", " 28013 Madrid", " Spain"]
splitAdress = splitAdress[2].split(" ");
//This will give you ["", "28013", "Madrid"]

You'll first split the string into an array based on the comma and then follow it up by splitting on the space. 您将首先基于逗号将字符串拆分为一个数组,然后通过在空格上拆分来进行后续处理。 The extra element in the second array is due to the space. 第二个数组中的多余元素是由于空间。 This is an example of what @CBroe pointed out in the comments. 这是@CBroe在注释中指出的示例。

list=adress.split(",")[2].split()

list[0] gives you the postal code list [0]为您提供邮政编码

list[1] gives you the city name list [1]为您提供城市名称

It depend on if there is always a comma in the "Calle Gran Vía, 8", if not you can use instead list=adress.split(",")[-2].split() 它取决于“ Calle list=adress.split(",")[-2].split() ,8”中是否始终有逗号,否则,可以使用list=adress.split(",")[-2].split()

You might want to try this. 您可能想尝试一下。

var address="Calle Gran Vía, 8, 28013 Madrid, Spain";
var splits = address.split(',')[2].trim().split(' ');
var newAdd = {
    city : splits[1],
    postal_code : splits[0]
}
console.log(newAdd);

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

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