我有一个字符串格式如下:
城市,州ZIP
我想从这个字符串中获取City和State。
我怎样才能用JavaScript做到这一点? 编辑请注意,他没有提到他到达这里时已经有了邮政编码,如果这对您的解决方案有帮助~~ drachenstern
答案 0 :(得分:10)
var address = "San Francisco, CA 94129";
function parseAddress(address) {
// Make sure the address is a string.
if (typeof address !== "string") throw "Address is not a string.";
// Trim the address.
address = address.trim();
// Make an object to contain the data.
var returned = {};
// Find the comma.
var comma = address.indexOf(',');
// Pull out the city.
returned.city = address.slice(0, comma);
// Get everything after the city.
var after = address.substring(comma + 2); // The string after the comma, +2 so that we skip the comma and the space.
// Find the space.
var space = after.lastIndexOf(' ');
// Pull out the state.
returned.state = after.slice(0, space);
// Pull out the zip code.
returned.zip = after.substring(space + 1);
// Return the data.
return returned;
}
address = parseAddress(address);
这可能比使用正则表达式和String.split()更好,因为它考虑到州和城市可能有空格。
编辑:错误修复:它只包含多字状态名称的第一个单词。
这是一个缩小版。 :d
function parseAddress(a) {if(typeof a!=="string") throw "Address is not a string.";a=a.trim();var r={},c=a.indexOf(',');r.city=a.slice(0,c);var f=a.substring(c+2),s=f.lastIndexOf(' ');r.state=f.slice(0,s);r.zip=f.substring(s+1);return r;}
答案 1 :(得分:2)
有很多方法可以做到这一点。这是一个非常天真的人:
var parts = "City, State ZIP".split(/\s+/); // split on whitespace
var city = parts[0].slice(0, parts[0].length - 1); // remove trailing comma
var state = parts[1];
var zip = parts[2];
这是一个考虑城市或州或两者中是否存在空间的人:
var parts = "san fran bay, new mex state 666666".split(/\s+|,/),
partition = parts.indexOf(""),
city = parts.slice(0, partition).join(" "),
state = parts.slice(partition + 1, -1).join(" "),
zip = parts.pop();
这最后一个只有在你足够幸运能够进入支持destructuring assignment的环境时才有效:
var city, statezip, state, zip, parts;
[city, statezip] = "Spaced City, New Mexico ZIP".split(/,\s*/);
parts = statezip.split(/\s+/);
zip = parts.pop();
state = parts.join(" ");
当然,这些都不会进行任何验证。
答案 2 :(得分:1)
好的,因为建议正则表达式不好,这是我的解决方案。它考虑了其中有空格的城市,其他答案似乎没有:
var str = "New York, NY 20101";
var cityAndRest = str.split(',');
var city = cityAndRest[0];
var stateAndZip = cityAndRest[1].trim().split(' ');
var state = stateAndZip[0];
var zip = stateAndZip[1];
答案 3 :(得分:0)
第一个假设:仅美国地址。
首先查明最后5个或最后10个字符是否为数字。更简单的测试是查看最后一个字符是否为数字。如果是这样,它可能包含了邮政编码。然后进行一个简单的测试,看看最后10个是否包含空格(city #####
),或者最后10个是否包含短划线(12345-6789
)以确定它是5还是5 + 4拉链。我们将测试一个连字符,没有空格。 (city-du-lac 12345
捕获-lac 12345
)
接下来,所有地址都用逗号分隔城市和州,所以我们想要最后一个逗号。找到最后一个逗号的索引,并在那里拆分。我不知道一个城市使用逗号的名字,如果我能帮助它,我肯定不会让我的解析器突然爆发。我确实忽略了Washington DC
也可能是Washington, DC
的事实。我认为边缘情况适用于库,而不是一个脚本。
最后,修剪剩下的所有内容以删除尾随或前导空格。
function IsNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var addr = 'New York City, New York 10101';
//var addr = 'San Bernadino, CA 11111';
function getCityStateZip(addr){
var city; var state;var zip;
city = ''; state = ''; zip = '';
var addrLen = addr.length;
if ( IsNumeric( addr.substring(addrLen - 1) ) ) {
//contains a zipcode - just a sanity check
//get last 10 characters for testing easily
var lastTen = addr.substring( addrLen - 10 );
if ( lastTen.indexOf('-') > 0 && ( lastTen.indexOf(' ') == -1 ) ) {
//found a hyphen and no space (matches our complex rule for zipcodes)
zip = lastTen;
} else {
zip = addr.substring( addrLen - 5 ); //assume a basic 5 zip code
}
}
var zipLen = zip.length;
addrLen = addrLen - zipLen - 1;
addr = addr.substring(0, addrLen ); //remove the chars we just moved into zip
var lastComma = addr.lastIndexOf(',');
if ( lastComma == -1 ) {
//you have a problem, how do you want to handle it?
}
city = addr.substring(0,lastComma); //skip the comma itself, yes?
state = addr.substring(lastComma + 2);
return { 'city':city,'state': state,'zip': zip};
}
getCityStateZip(addr)
IsNumeric
js函数可以在Validate decimal numbers in JavaScript - IsNumeric()
答案 4 :(得分:0)
简单的方法但没有验证:
var addrObj={};
parseAddress("Beverly Hills, CA 90210",addrObj);
function parseAddress(address, addrObj){
var arr=address.replace(","," ").split(" ");
addrObj.zip=arr.pop();
addrObj.state=arr.pop();
addrObj.city=arr.join(" ");
}
答案 5 :(得分:-1)