How to Convert Comma Separated String to an Array in JavaScript

Here are three ways to convert comma separated string to an array in JavaScript:

  1. Using split() method
  2. Using for loop and slice() method
  3. Using Array.from() and string.split() method

Method 1: Using split() method

In JavaScript, you can easily convert a comma-separated string into an array “using the split() method of the String object.”

Syntax

string.split(', ')

Example

let commaSeparatedString = "apple,banana,cherry";
let array = commaSeparatedString.split(",");

console.log(array);

Output

[ 'apple', 'banana', 'cherry' ]

If there might be spaces after the commas (like “apple, banana, cherry”), and you want to remove them, you can use the map() method in combination with the trim() method:

let commaSeparatedString = "apple,banana,cherry";
let array = commaSeparatedString.split(",").map(item => item.trim());

console.log(array);

Output

[ 'apple', 'banana', 'cherry' ]

Method 2: Using for loop and slice() method

Here’s an example where we will slice out every 3 characters from the string “RameshbabuCarlsen” using a for loop and slice() method.

Syntax

string.slice(startingIndex, endingIndex)

Example

let str = "Rameshbabu Carlsen";
let step = 3;
let result = [];

for (let i = 0; i < str.length; i += step) {
  let substring = str.slice(i, i + step);
  result.push(substring);
}

console.log(result);

Output

[ 'Ram', 'esh', 'bab', 'u C', 'arl', 'sen' ]

Method 3: Using Array.from() and string.split() method

The Array.from() method is used to create a new array instance from an array-like or iterable object. On the other hand, the string.split() method splits a string into an array of substrings based on a specified separator.

Combining these two might seem redundant in many cases, as string.split() itself already produces an array. However, there are some specific scenarios where combining them can be useful.

Syntax

Array.from(object, mapFunction, thisValue)

Example

let str = "MagnusCarlsen";
let array = Array.from(str.split(""));

console.log(array);

Output

Using Array.from() and string.split() method

However, if you want to use Array.from() with its optional map() function argument alongside .split(), it becomes more meaningful.

Here’s an example where we split a string by spaces and then use the map function to return the length of each word:

let sentence = "India is on the moon";
let lengths = Array.from(sentence.split(" "), word => word.length);

console.log(lengths);

Output

[ 5, 2, 2, 3, 4 ]

That’s it!

Related posts

JavaScript array to csv

JavaScript csv to array

JavaScript array to lowercase

JavaScript string to title case

JavaScript set to array

Leave a Comment