399

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

13 Answers 13

594
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.

2
  • 43
    This will not work if the string being searched does not contain an instance of the search character. It will return an empty string.
    – David G
    Commented Aug 20, 2015 at 19:48
  • 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.. Commented Jul 4 at 14:38
262
var streetaddress = addy.split(',')[0];
5
  • 20
    swings and roundabouts - it unnecessarily creates an array, but does at least work if the stop character isn't in the string
    – Alnitak
    Commented Jan 30, 2017 at 11:28
  • 2
    For performance comparison, see: jsperf.com/street-array-vs-substr
    – Blue
    Commented Nov 30, 2017 at 13:17
  • 6
    previous comment link is dead :/
    – elki42
    Commented Jun 27, 2019 at 11:13
  • As mentioned by @Alnitak, this option is best if the stop character isn't in the string.
    – Yannick T.
    Commented Mar 23, 2022 at 18:09
  • 5
    Consider addy.split(",", 1)[0] which stops splitting after the first occurrence of ",". Commented Dec 26, 2022 at 2:16
47

try this:

streetaddress.substring(0, streetaddress.indexOf(','));
2
  • 2
    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.
    – Mikey G
    Commented Aug 5, 2015 at 20:53
  • 12
    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 Commented Jan 23, 2017 at 10:51
41
//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
  • This is better than the method using indexof, in the scenario where there is no comma character
    – eyal_katz
    Commented Jan 22, 2017 at 19:17
  • 5
    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/….
    – flu
    Commented Oct 12, 2017 at 8:16
  • 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>) Commented Aug 31, 2018 at 22:37
  • 4
    Isn't this answer exactly the same as the answer posted on Oct 30, 2015?
    – kojow7
    Commented Jan 7, 2020 at 20:19
22

If you like it short simply use a RegExp:

var streetAddress = /[^,]*/.exec(addy)[0];
3
  • 4
    +1, I think this is a reasonable method, but I took a hint from this and went with addy.split(',', 1)[0]
    – antak
    Commented Aug 8, 2014 at 5:39
  • 3
    This method is very nice for example if you want to split on white space: /[^\s]*/.exec(...)
    – NuSkooler
    Commented Aug 1, 2015 at 18:08
  • When the remove substring does not neccesarily exist: streetAddress = addy.replace(/,.*$/, '');, this removes everything after the first match (of ,) only if it exists
    – miile7
    Commented Nov 30, 2021 at 9:41
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
  • 2
    Indexing with [0] is more efficient than using .shift() Commented Oct 5, 2018 at 0:11
  • Warning: if input string doesn't contain comma, it the entire string will be returned.
    – izogfif
    Commented Sep 9, 2022 at 11:33
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.

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

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

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,',');
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
  • regex that is difficult, big mechanism and it has bad performance, we need avoid using it Commented May 2, 2023 at 13:57
1

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

function getStreetAddress(str: string, separator = ','): string {
  const separatorIndex = path.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.

-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
  • .indexOf() returns -1 if the needle is not found. Therefore addy.length will never be chosen. Commented Jul 28, 2022 at 6:15
  • Of course, you're right. Corrected.
    – monkey
    Commented Jul 31, 2022 at 7:31

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.