How to grab substring before a specified character jQuery or JavaScript

How to grab substring before a specified character jQuery or JavaScript

I am trying to extract everything before the ‘,’ comma. How do I do this in JavaScript or jQuery? I tried this and not working..
1345 albany street, Bellevue WA 42344

I just want to grab the street address.
var streetaddress= substr(addy, 0, index(addy, ‘.’));


Solution 1:

var streetaddress= addy.substr(0, addy.indexOf(',')); 

While it’s not the best place for definitive information on what each method does (mozilla developer network is better for that) is good for introducing you to syntax.

Solution 2:

var streetaddress = addy.split(',')[0];

Solution 3:

try this:

streetaddress.substring(0, streetaddress.indexOf(','));

Solution 4:

//split string into an array and grab the first item

var streetaddress = addy.split(',')[0];

Also, I’d recommend naming your variables with camel-case(streetAddress) for better readability.

Solution 5:

If you like it short simply use a RegExp:

var streetAddress = /[^,]*/.exec(addy)[0];

Solution 6:

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.

Related:  WebRTC can't get a video feed from a USB input device (readyState goes to ended)

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.