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"]
0

1 Answer 1

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

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

4 Comments

Note that this actually results in the array being ["football", "tennis, basketball", ""]
@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.
@SnoringFrog There, now I overwrite my array variable instead of outputting the result? Does that cause less confusion?
That creates the array value OP was expecting/asking for, yes

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.