Search code examples
javascriptstringstreet-address

Address String Split in javascript


Ok folks I have bombed around for a few days trying to find a good solution for this one. What I have is two possible address formats.

28 Main St Somecity, NY 12345-6789    
or 
Main St Somecity, Ny 12345-6789

What I need to do Is split both strings down into an array structured as such

address[0] = HousNumber 
address[1] = Street 
address[2] = City 
address[3] = State 
address[4] = ZipCode

My major problem is how to account for the lack of a house number. with out having the whole array shift the data up one.

address[0] = Street 
address[1] = City 
address[2] = State 
address[3] = ZipCode

[Edit]

For those that are wondering this is what i am doing atm . (cleaner version)

     place = response.Placemark[0];
        point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
    FCmap.setCenter(point,12);


        var a = place.address.split(',');

        var e = a[2].split(" ");

        var x = a[0].split(" ");

        var hn = x.filter(function(item,index){
            return index == 0;
        });

                var st = x.filter(function(item,index){
                    return index != 0;
                });

                var street = ''; 

                st.each(function(item,index){street += item + ' ';});

        results[0] = new Hash({
                        FullAddie:  place.address,
                        HouseNum:   hn[0],
                        Dir:        '',
                        Street:     street,
                        City:       a[1],
                        State:      e[1],
                        ZipCode:    e[2],
                        GPoint:     new GMarker(point),
                        Lat:        place.Point.coordinates[1],
                        Lng:        place.Point.coordinates[0]
                        });
        // End Address Splitting 

Solution

  • Reverse the string, do the split and then reverse each item.

    Update: From the snippet you posted, it seems to me that you get the address from a Google GClientGeocoder Placemark. If that is correct, why are you getting the unstructured address (Placemark.address) instead of the structured one (Placemark.AddressDetails)? This would make your life easier, as you would have to try and parse only the ThoroughfareName, which is the street level part of the address, instead of having to parse everything else as well.