245

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

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
user649802
  • 3,243
  • 3
  • 20
  • 14
  • 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

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

split()

alex
  • 479,566
  • 201
  • 878
  • 984
117
var array = string.split(',')

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

thomas
  • 2,297
  • 2
  • 22
  • 23
109

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

More info on W3Schools describing the String Split function.

Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161
Ralf de Kleine
  • 11,464
  • 5
  • 45
  • 87
  • 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,908
  • 70
  • 97
  • 130