246

I want to split a comma separated string with JavaScript. How?

5
  • Does any of these any of these answers produce trimmed values? They're not. Commented Oct 22, 2013 at 7:46
  • 1
    @NK The OP didn't ask about trimming the values, though. Splitting on ',' is similar enough to splitting on '~' that it seems like this really is a duplicate. Commented Oct 22, 2013 at 14:44
  • @JoshuaTaylor, ideally splitting csv should produce a splitted and trimmed output Commented Oct 23, 2013 at 4:11
  • 1
    @NK I'm not aware of an authoritative standard for CSV which states this (but there might be such a thing; I'm just not aware of it), but even if there is, the OP didn't ask for trimmed strings in the result. As the question is phrased, it's a duplicate of the other. If the requirement included trimmed spaces, then the OP always has the option to edit the question, at which point it might be reopened. Second-guessing the requirements and intent of a question-asker is useful sometimes, but sometimes its the path to unhelpful answers. Commented Oct 23, 2013 at 12:14
  • As the OP does not accept any of the given answers (every answers are same and similar to original marked question), OP might not satisfy with the given answers or he didn't get a solution for his requirement. Commented Oct 23, 2013 at 12:31

4 Answers 4

361
var partsOfStr = str.split(',');

split()

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

5 Comments

@Andrew That's an entirely different question. Please read this one again.
remove any garbage (") server-side before its presented to JS
& you can use .join() to put them back together again
@alex what if I have in str {a: 'a'} how can I stop the split function to split this object, and only work on a list of elements?
fails miserably when a field value contains a comma. obviously.
118
var array = string.split(',')

and good morning, too, since I have to type 30 chars ...

Comments

110

var result;
result = "1,2,3".split(","); 
console.log(result);

More info on W3Schools describing the String Split function.

2 Comments

Parse result like this "val1 with extra, here",val2,val3
@Andrew The code will work perfectly to do that. If you want code to split on , and take into account quoted values, ask a new question :)
29

Use

YourCommaSeparatedString.split(',');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.