我有一个具有以下格式的字符串:
City, State ZIP
我想从这个字符串中获取城市和州。
我如何使用 JavaScript 做到这一点? 编辑: 请注意,他没有提到他到达这里时已经有了邮政编码,如果这对您的解决方案有帮助的话 ~~ drachenstern
最佳答案
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;}
关于javascript - 帮助使用 JavaScript 解析字符串(城市、州 zip ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5097875/