To convert a comma separated string into an array in JavaScript, you can use the string.split()
method. The split()
method lets you split a string at a given character and returns an array as a result.
Here is its syntax:
str.split(separator, limit)
So, if you want to split the string at each occurrence of a comma(,)
, you have to pass a comma(',')
as a separator to the split()
method.
See the following example:
let str = 'apple,banana,mango,orange'; let arr = str.split(','); console.log(arr); // Output 👇 // ["apple", "banana", "mango", "orange"]
If the string you want to split has spaces after commas, then in the separator, you have to put a space after the comma too.
See the following example:
let str = 'apple, banana, mango, orange'; let arr = str.split(', '); console.log(arr); // Output 👇 // ["apple", "banana", "mango", "orange"]
In case, the string we want to split at each comma is empty, then the resulting array will not be empty, instead, it will contain an empty string.
See the following example:
let str = ''; let arr = str.split(','); console.log(arr); // Output 👇 // [""]