javascript - 帮助使用 JavaScript 解析字符串(城市、州 zip )

标签 javascript regex parsing

我有一个具有以下格式的字符串:

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/

相关文章:

Python 字符串拆分为多个字符

java - 让正则表达式在 Java 中工作

php - 从 PHP 中的函数生成正则表达式

c - 将十六进制字符串表示形式解析为整数

android - Android 版 Mp4Parser

javascript - 特定迭代的循环延迟

javascript - 鼠标拖动滚动元素,具有 iPhone/Android 效果

javascript - javascript中svg的随机路径

javascript - 找到一种使用 Google Maps API 通过回调传递信息的好方法

php - 在 PHP 中解析时取消格式货币