0

I'm having a string like below that i would like to split only on the first ,. so that if i for instance had following string Football, tennis, basketball it would look like following array

["football", "tennis, basketball"]
Peter Pik
  • 11,023
  • 19
  • 84
  • 142

1 Answers1

0

This should do it

var array = "football, tennis, basketball".split(/, ?(.+)?/);
array = [array[0], array[1]];
console.log(array);

Inspiration: split string only on first instance of specified character


EDIT

I've actually found a way to reduce the above function to one line:

console.log("football, tennis, basketball".split(/, ?(.+)?/).filter(Boolean));

.filter(Boolean) is used to trim off the last element of the array (which is just an empty string).

Community
  • 1
  • 1
ctwheels
  • 21,901
  • 9
  • 42
  • 77
  • Note that this actually results in the `array` being `["football", "tennis, basketball", ""]` – SnoringFrog Sep 22 '16 at 16:03
  • @SnoringFrog No it doesn't. Overwrite the `array` variable with what I put in the `console.log`. That's the correct answer. You are not outputting the same value as the above function. – ctwheels Sep 22 '16 at 16:04
  • @SnoringFrog There, now I overwrite my array variable instead of outputting the result? Does that cause less confusion? – ctwheels Sep 22 '16 at 16:11
  • That creates the `array` value OP was expecting/asking for, yes – SnoringFrog Sep 22 '16 at 16:13