Let’s say I have this string:
<div>john doe is nice guy btw 8240 E. Marblehead Way 92808 is also</div>
or this string:
<div>sky being blue? in the world is true? 024 Brea Mall Brea, California 92821 jackfroast nipping on the firehead</div>
How would I go about extracting the address from one of these strings? This would involve some sort of Regex, right?
I’ve tried looking online for a solution using JavaScript or PHP, but to no avail.
And no other post here on Stack Overflow (as far as I know) provides a solution that uses jQuery and/or Javascript and/or PHP. (The closest is Parse usable Street Address, City, State, Zip from a string, which DOESN’T have any code in the thread about extracting a postal code from a string.
Can somebody point me in the right direction? How would I go about accomplishing this in jQuery or JavaScript or PHP?
Tried this on twelve different strings that were similar to yours and it worked just fine:
This assumes a house number of at least two digits, and no greater than six. This also assumes that the zip code isn’t in the “expanded” form (e.g. 12345-6789). However this can be easily modified to fit that format (regex would be a good option here, something like
(\d{5}-\d{4}).But using regex for parsing user-inputted data… Not a good idea here, because we just don’t know what a user is going to input because there were (as one can assume) no validations.
Walking through the code and logic, starting with creating the array from the context and grabbing the zip:
Do some tidying so we have a better object to garb the house number from
And then let’s grab the house number, using the same basic logic that we did the zip code: