Javascript 将目的地分为城市、地区和国家
我有一根绳子Javascript 将目的地分为城市、地区和国家,javascript,regex,Javascript,Regex,我有一根绳子 var str = "Orlando (and vicinity), Florida, United States of America"; 我想拆分这个字符串,用Javascript保存城市、地区和国家 Eg: city - Orlando region - Florida country - United States Of America 这将基于拆分创建一个包含key:values的对象: let str = "Orlando (and vicinity
var str = "Orlando (and vicinity), Florida, United States of America";
我想拆分这个字符串,用Javascript保存城市、地区和国家
Eg: city - Orlando
region - Florida
country - United States Of America
这将基于拆分创建一个包含key:values的对象:
let str = "Orlando (and vicinity), Florida, United States of America";
let locationData = {city: "", region: "", country: ""};
let result = str.split(",")
locationData.city = result[0];
locationData.region = result[1];
locationData.country = result[2];
但是,像这样拆分字符串是不可靠的。尝试下面的方法,我已将它们插入到对象中 var str=美国佛罗里达州奥兰多及其附近地区; 数据=str.split',' 城市=数据[0]。匹配/^\w+/g res={ “城市”:城市[0], “区域”:数据[1], “国家”:数据[2] }
console.logres您的意思是使用commasplit on进行拆分,这将是一种方法。拆分/\s*,\s*/g可修剪生成的字符串。用逗号。