regex - Help parsing string (City, State Zip) with JavaScript -
i've got string following format:
city, state zip
i'd city , state string.
how can javascript? edit: note doesn't mention has zip code when gets here, if helps in solution ~~ drachenstern
var address = "san francisco, ca 94129"; function parseaddress(address) { // make sure address string. if (typeof address !== "string") throw "address not string."; // trim address. address = address.trim(); // make object contain data. var returned = {}; // find comma. var comma = address.indexof(','); // pull out city. returned.city = address.slice(0, comma); // after city. var after = address.substring(comma + 2); // string after comma, +2 skip comma , space. // find space. var space = after.lastindexof(' '); // pull out state. returned.state = after.slice(0, space); // pull out zip code. returned.zip = after.substring(space + 1); // return data. return returned; } address = parseaddress(address);
this better using regular expressions , string.split(), takes account state , city may have spaces.
edit: bug fix: included first word of multi-word state names.
and here's minified version. :d
function parseaddress(a) {if(typeof a!=="string") throw "address not 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;}
Comments
Post a Comment