Convert comma-separated string to array in JavaScript
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:
|
1 2 3 4 5 |
let str = "red,green,blue"; let arr = str.split(","); console.log(arr); // ["red", "green", "blue"] |
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:
|
1 2 3 4 5 6 |
let str = "red,green,blue"; // Match any character except comma let arr = str.match(/[^,]+/g); console.log(arr); // ["red", "green", "blue"] |
That’s all about converting a comma-separated string to an array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)