published: 22 Apr 2022
2 min read
How to convert an array to a string in JavaScript
To convert an array to a string in JavaScript:
- Call the
Array.join()
method on the array. - Pass in an optional separator. The default separator is the comma (
,
). - The
Array.join()
method returns array values joined by the separator as a string
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.
Read this guide to learn more about JavaScript arrays and how to store multiple pieces of information in a single variable.
Are we missing something? Help us improve this article. Reach out to us.
How to convert an array to a string in JavaScript
To convert an array to a string in JavaScript:
- Call the
Array.join()
method on the array. - Pass in an optional separator. The default separator is the comma (
,
). - The
Array.join()
method returns array values joined by the separator as a string
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.
Read this guide to learn more about JavaScript arrays and how to store multiple pieces of information in a single variable.
Are you looking for other code tips?
JS Nooby
Javascript connoisseur