In vanilla JavaScript, you can use the Array.join()
method to convert an array into a human-readable string. This method takes an array as input and returns the array as a string.
By default, the elements are joined together by using a comma (,
) as a separator:
const fruits = ['Apple', 'Orange', 'Mango', 'Cherry'];
const str = fruits.join();
console.log(str);
// Apple,Orange,Mango,Cherry
You can also specify a custom separator — dashes, spaces, or empty strings — as a parameter to the Array.join()
method. Let us say that you want to add a space after the comma, just pass the following to Array.join()
:
const str = fruits.join(', ');
// Apple, Orange, Mango, Cherry
Want to have each array element on its own line? Just pass in a newline character:
const str = fruits.join('\n');
// Apple
// Orange
// Mango
// Cherry
Prefer to use the HTML line break?
const str = fruits.join('<br>');
The Array.join()
method works in all modern browsers, and back to at least IE6.
Take a look at this guide to learn more about JavaScript arrays and how to use them to store multiple pieces of information in a single variable.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.