1345 albany street, Bellevue WA 42344
I just want to grab the street address.
var streetaddress= substr(addy, 0, index(addy, ‘.’));
var streetaddress= addy.substr(0, addy.indexOf(','));
var streetaddress = addy.split(',');
//split string into an array and grab the first item var streetaddress = addy.split(',');
Also, I’d recommend naming your variables with camel-case(streetAddress) for better readability.
If you like it short simply use a RegExp:
var streetAddress = /[^,]*/.exec(addy);
almost the same thing as David G’s answer but without the anonymous function, if you don’t feel like including one.
s = s.substr(0, s.indexOf(',') === -1 ? s.length : s.indexOf(','));
in this case we make use of the fact that the second argument of
substr is a length, and that we know our substring is starting at 0.
the top answer is not a generic solution because of the undesirable behavior if the string doesn’t contain the character you are looking for.
if you want correct behavior in a generic case, use this method or David G’s method, not the top answer
regex and split methods will also work, but may be somewhat slower / overkill for this specific problem.