How to grab substring before a specified character in JavaScript?
Asked Answered
S

13

394

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, '.')); 
Sudden answered 3/2, 2012 at 17:49 Comment(1)
addy.split(',', 1)[0]Floeter
S
587
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.

Sea answered 3/2, 2012 at 17:57 Comment(1)
This will not work if the string being searched does not contain an instance of the search character. It will return an empty string.Towney
T
257
var streetaddress = addy.split(',')[0];
Tannatannage answered 30/10, 2015 at 13:57 Comment(5)
swings and roundabouts - it unnecessarily creates an array, but does at least work if the stop character isn't in the stringSelfdeprecating
For performance comparison, see: jsperf.com/street-array-vs-substrPassport
previous comment link is dead :/Trisoctahedron
As mentioned by @Alnitak, this option is best if the stop character isn't in the string.Devan
Consider addy.split(",", 1)[0] which stops splitting after the first occurrence of ",".Wheelwork
E
47

try this:

streetaddress.substring(0, streetaddress.indexOf(','));
Erleneerlewine answered 3/2, 2012 at 17:54 Comment(2)
Why no love for my answer? If this answer is correct #3746015 my answer is as accurate as the accepted answer, and works for starting indices other than 0.Erleneerlewine
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/13pkp1xnMaking
D
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.

Dispend answered 15/3, 2016 at 16:35 Comment(4)
This is better than the method using indexof, in the scenario where there is no comma characterSeddon
You can save some processing and stop splitting at the first "," found by using what @Floeter posted as a comment in https://mcmap.net/q/86646/-how-to-grab-substring-before-a-specified-character-in-javascript: addy.split(',', 1)[0]. See developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/….Tema
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>)Fairy
Isn't this answer exactly the same as the answer posted on Oct 30, 2015?Crossley
T
22

If you like it short simply use a RegExp:

var streetAddress = /[^,]*/.exec(addy)[0];
Tema answered 13/3, 2014 at 17:28 Comment(3)
+1, I think this is a reasonable method, but I took a hint from this and went with addy.split(',', 1)[0]Floeter
This method is very nice for example if you want to split on white space: /[^\s]*/.exec(...)Kangaroo
When the remove substring does not neccesarily exist: streetAddress = addy.replace(/,.*$/, '');, this removes everything after the first match (of ,) only if it existsAcaudal
P
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

Population answered 24/4, 2018 at 20:10 Comment(2)
Indexing with [0] is more efficient than using .shift()Cawley
Warning: if input string doesn't contain comma, it the entire string will be returned.Malanie
C
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.

Cautious answered 10/3, 2016 at 15:51 Comment(0)
A
9
var newString = string.substr(0,string.indexOf(','));
Assiduous answered 3/2, 2012 at 17:52 Comment(0)
M
8
var streetaddress = addy.substr(0, addy.indexOf('.')); 

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

Mayman answered 3/2, 2012 at 17:52 Comment(0)
T
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,',');
Towney answered 21/8, 2015 at 16:23 Comment(0)
H
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.

Handspike answered 16/1, 2020 at 10:44 Comment(1)
regex that is difficult, big mechanism and it has bad performance, we need avoid using itPermeate
S
0

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.

Sober answered 9/2 at 20:45 Comment(0)
B
-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.

Blacktail answered 26/5, 2022 at 1:7 Comment(2)
.indexOf() returns -1 if the needle is not found. Therefore addy.length will never be chosen.Feodora
Of course, you're right. Corrected.Blacktail

© 2022 - 2024 — McMap. All rights reserved.