How to Convert a Comma-Separated String into Array in JavaScript

In JavaScript, it’s common to work with strings that contain a list of items separated by a delimiter like a comma.

For instance, you may receive a string like “apple, banana, cherry, date” from an API or a user input.

In such cases, it is necessary to convert the comma-separated string into an array to work with the individual items.

In this Javascript tutorial, we’ll explore several methods to convert a comma-separated string into an array in JavaScript.


Split Method

The easiest and most straightforward method to convert a comma-separated string into an array is to use the split method.

The split method takes a string and splits it into an array of substrings based on the specified delimiter.

Here’s an example of how to use the split method:

let fruitString = "apple, banana, cherry, date";
let fruitArray = fruitString.split(', ');
console.log(fruitArray); // Output: [ "apple", "banana", "cherry", "date" ]

Using a Loop

Another way to convert a comma-separated string into an array is to use a loop.

This method is useful when the delimiter is not always a comma.

In this method, we use the JavaScript built-in string method charAt to iterate over each character in the string and push individual items into an array.

Here’s an example of how to use a loop:

let fruitString = "apple, banana, cherry, date";
let fruitArray = [];
let currentItem = '';

for (let i = 0; i < fruitString.length; i++) {
  let char = fruitString.charAt(i);
  
  if (char === ',') {
    fruitArray.push(currentItem);
    currentItem = '';
  } else {
    currentItem += char;
  }
}

// Push the last item
fruitArray.push(currentItem);

console.log(fruitArray); // Output: [ "apple", "banana", "cherry", "date" ]

Using Regular Expressions

Regular expressions are a powerful tool in JavaScript for pattern matching and manipulation of strings.

We can use a regular expression to split a string into an array.

Here’s an example of how to use regular expressions:

let fruitString = "apple, banana, cherry, date";
let fruitArray = fruitString.split(/,\s*/);
console.log(fruitArray); // Output: [ "apple", "banana", "cherry", "date" ]

Conclusion

In this tutorial, we explored three methods to convert a comma-separated string into an array in JavaScript.

The split method is the simplest and most commonly used method, but in some cases, it may be necessary to use a loop or regular expressions.

Choose the method that best fits your use case and start working with the individual items in your arrays.