Convert comma separated string to an array in JavaScript

In this article, you are going to learn how to convert a comma separated string into an array in JavaScript. All the elements of our array will hold the items separated by commas.

To achieve the task, we are going to use the JavaScript string split() method. Using this method, all we have to do is to provide the separator which will separate the string into parts. As we want to separate our comma-separated string into an array, so in our case, the separator will be the comma.

For example, suppose we have the name of some colors separated by comma just like you can see below:

green,red,blue,white,black,indigo,gray,yellow

Now we will take it as a string. Here we are going to use the split() method and use the comma as the separator of the string.

Below is the code which will convert our comma-separated string into an array in JavaScript:

var str = "green,red,blue,white,black,indigo,gray,yellow";
var spilitted_str = str.split(',');
console.log(spilitted_str);

Now we can see an array as the output that consists of each color separated by the comma as each array element.

The output array is given below:

["green", "red", "blue", "white", "black", "indigo", "gray", "yellow"]

You can clearly see that each of the array elements contains a color. The order of the colors is as same as we see it in our comma-separated string. This is because, we take comma (“,”) as the separator. So the method separates our string exactly from the commas and converts it into an array.

Also, read:

 

Leave a Reply

Your email address will not be published. Required fields are marked *