408

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, '.')); 
1
  • 58
    addy.split(',', 1)[0] Commented Aug 8, 2014 at 5:37

13 Answers 13

606
const streetAddress = addy.substring(0, addy.indexOf(","));

While it’s not the best place for definitive information on what each method does (MDN Web Docs are better for that) W3Schools.com is good for introducing you to syntax.

Sign up to request clarification or add additional context in comments.

2 Comments

This will not work if the string being searched does not contain an instance of the search character. It will return an empty string.
For me it is better, because my strings could be long and I do not need nothing more than few chars from start of original string..
267
var streetaddress = addy.split(',')[0];

5 Comments

swings and roundabouts - it unnecessarily creates an array, but does at least work if the stop character isn't in the string
For performance comparison, see: jsperf.com/street-array-vs-substr
previous comment link is dead :/
As mentioned by @Alnitak, this option is best if the stop character isn't in the string.
Consider addy.split(",", 1)[0] which stops splitting after the first occurrence of ",".
46

try this:

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

2 Comments

Why no love for my answer? If this answer is correct stackoverflow.com/questions/3745515/… my answer is as accurate as the accepted answer, and works for starting indices other than 0.
As pointed out by David G above, possibly because it doesn't work if there is no comma. The OP may have implied that the string would always have a comma, but in many instances the delimiter is not guaranteed. See jsfiddle.net/13pkp1xn
42
//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.

4 Comments

This is better than the method using indexof, in the scenario where there is no comma character
You can save some processing and stop splitting at the first "," found by using what @antak posted as a comment in stackoverflow.com/a/22386366/601386: addy.split(',', 1)[0]. See developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/….
Using array deconstruction, you could do: const [streetAddress,] = addy.split(','); This is helpful for cases when you want more than one value, such as: let [callerIdName, callerId] = callerIdString.split('<'); (original callerIdString format is MCMULLIN,PARKER <+1XXXXXXXXXX>)
Isn't this answer exactly the same as the answer posted on Oct 30, 2015?
22

If you like it short simply use a RegExp:

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

3 Comments

+1, I think this is a reasonable method, but I took a hint from this and went with addy.split(',', 1)[0]
This method is very nice for example if you want to split on white space: /[^\s]*/.exec(...)
When the remove substring does not neccesarily exist: streetAddress = addy.replace(/,.*$/, '');, this removes everything after the first match (of ,) only if it exists
21

You can also use shift().

var streetaddress = addy.split(',').shift();

According to MDN Web Docs:

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

2 Comments

Indexing with [0] is more efficient than using .shift()
Warning: if input string doesn't contain comma, it the entire string will be returned.
13

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.

Comments

9
var newString = string.substr(0,string.indexOf(','));

Comments

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

(You should read through a javascript tutorial, esp. the part about String functions)

Comments

2

If you want to return the original string untouched if it does not contain the search character then you can use an anonymous function (a closure):

var streetaddress=(function(s){var i=s.indexOf(',');
   return i==-1 ? s : s.substr(0,i);})(addy);

This can be made more generic:

var streetaddress=(function(s,c){var i=s.indexOf(c);
   return i==-1 ? s : s.substr(0,i);})(addy,',');

Comments

2

You could use regex as this will give you the string if it matches the requirements. The code would be something like:

const address = "1345 albany street, Bellevue WA 42344";
const regex = /[1-9][0-9]* [a-zA-Z]+ [a-zA-Z]+/;
const matchedResult = address.match(regex);

console.log(matchedResult[0]); // This will give you 1345 albany street.

So to break the code down. [1-9][0-9]* basically means the first number cannot be a zero and has to be a number between 1-9 and the next number can be any number from 0-9 and can occur zero or more times as sometimes the number is just one digit and then it matches a space. [a-zA-Z] basically matches all capital letters to small letters and has to occur one or more times and this is repeated.

1 Comment

regex that is difficult, big mechanism and it has bad performance, we need avoid using it
1

According to the ESLint rule prefer-string-slice, here is my implementation using slice() method:

function getStreetAddress(str: string, separator = ','): string {
  const separatorIndex = str.indexOf(separator);

  return separatorIndex === -1 ? str : str.slice(0, separatorIndex);
}

It returns the whole string if the separator has not been found.

Worth to mention, as it seems you're trying to parse a kind of CSV file row, this code may work in your case, but not when the street address contains special characters or the separator itself (,). To do so, fields in CSV files may be wrapped with quotes, which is not handled in this simple implementation.

Comments

-1

If you are worried about catching the case where no comma is present, you could just do this:

let end = addy.indexOf(",") >= 0 ? addy.indexOf(",") : addy.length;
let streetaddress = addy.substr(0, end);

Nobody said it had to go on one line.

2 Comments

.indexOf() returns -1 if the needle is not found. Therefore addy.length will never be chosen.
Of course, you're right. Corrected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.