For example, suppose we have the name of some colors separated by comma just like you can see below:
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.
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.