使用JavaScript帮助解析字符串(City,State Zip)

Mos*_*she 5 javascript regex parsing

我有一个字符串,格式如下:

邮政编码

我想从这个字符串中获取City和State.

我怎么能用JavaScript做到这一点?编辑:请注意,他没有提到他到达这里时已经有了邮政编码,如果这有助于你解决问题~~ drachenstern

McK*_*yla 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);
Run Code Online (Sandbox Code Playgroud)

这可能比使用正则表达式和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;}
Run Code Online (Sandbox Code Playgroud)