This post will discuss how to convert a comma-separated string to an array in JavaScript.

A comma-separated string is a string that contains a list of values separated by commas, such as "red,green,blue". We need to convert such string to the corresponding array ["red", "green", "blue"]. Here are some of the methods we can use to convert a comma-separated string to an array:

1. Using String.split() function

The String.split() function splits a string into an array of substrings, using a specified separator as the delimiter. If we pass a comma as the separator, it will split the string into an array of strings that are separated by commas in the original string. Here’s an example:

Download  Run Code

2. Using String.match() function

The String.match() function returns an array of matches of a regular expression in a string. If we use a regular expression that matches any character except a comma, such as /[^,]+/g, the function will return an array of all the substrings that do not contain a comma. Here’s an example of this approach:

Download  Run Code

That’s all about converting a comma-separated string to an array in JavaScript.