242

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

Samuel Liew
  • 72,637
  • 105
  • 156
  • 238
user649802
  • 3,213
  • 3
  • 18
  • 13
  • Does any of these any of these answers produce trimmed values? They're not. – N K Oct 22 '13 at 07: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. – Joshua Taylor Oct 22 '13 at 14:44
  • @JoshuaTaylor, ideally splitting csv should produce a splitted and trimmed output – N K Oct 23 '13 at 04: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. – Joshua Taylor Oct 23 '13 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. – N K Oct 23 '13 at 12:31

4 Answers4

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

split()

alex
  • 460,746
  • 196
  • 858
  • 974
116
var array = string.split(',')

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

thomas
  • 2,257
  • 2
  • 21
  • 23
108

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

More info on W3Schools describing the String Split function.

Abrar Jahin
  • 13,156
  • 22
  • 105
  • 151
Ralf de Kleine
  • 11,054
  • 4
  • 40
  • 83
  • Parse result like this `"val1 with extra, here",val2,val3` – Andrew Dec 09 '15 at 20:30
  • @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 :) – alex May 11 '18 at 15:00
29

Use

YourCommaSeparatedString.split(',');
CloudyMarble
  • 36,156
  • 70
  • 93
  • 127