- Instant help with your JavaScript coding problems

Convert array to comma separated string using JavaScript

Question:
How to convert array to comma separated string using JavaScript?
Answer:
const myArray = ['apple', 'orange', 'banana', 'ananas'];

const csv1 = String(myArray); // apple,orange,banana,ananas
const csv2 = myArray.toString(); // apple,orange,banana,ananas
const csv3 = myArray.join(); // apple,orange,banana,ananas
const csv4 = myArray.join('; '); // apple; orange; banana; ananas
Description:

The easiest way to create CSV text from a plain array is to use the toString method or the String constructor in JavaScript. The advantage of the String constructor is that you do not have to check if the variable is indeed an array.

If you want a little more freedom, you can use the join method. The join() method creates and returns a new string by concatenating all of the elements in an array, separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

The separator can be any character, and you can even use a multi-character string.

Share "How to convert array to comma separated string using JavaScript?"