I want to split a comma separated string with JavaScript. How?
Asked
Active
Viewed 4.2e+01k times
245
-
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 Answers
355
-
2@Andrew That's an entirely different question. Please read this one again. – alex Dec 10 '15 at 08:57
-
-
-
@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? – Tenzolinho Mar 25 '20 at 14:59
-
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
-
-
@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