Convert an Array to a String in JavaScript


Borislav Hadzhiev

Wed Oct 20 20212 min read


Photo by Alex Wong

Convert an Array to a String in JavaScript #

To convert an array to a string, pass the array as a parameter to the String object - String(arr). The String object converts the passed in value to a string and returns the result.

const arr = ['one', 'two', 'three']; const str = String(arr); console.log(str); // ๐Ÿ‘‰๏ธ 'one,two,three' const strWithoutSeparator = arr.join(''); console.log(strWithoutSeparator); // ๐Ÿ‘‰๏ธ 'onetwothree' const strWithSeparator = arr.join('-'); console.log(strWithSeparator); // ๐Ÿ‘‰๏ธ 'one-two-three' const strWithSpace = arr.join(' '); console.log(strWithSpace); // ๐Ÿ‘‰๏ธ 'one two three' const stringified = JSON.stringify(arr); console.log(stringified); // ๐Ÿ‘‰๏ธ '["one", "two", "three"]'

In the first example we used the String object to convert the array to a string. This returns a comma-separated string containing the array elements.

However, in some situations we want to omit the commas.

In our second example, we use the Array.join method to join the array elements into a string.

The only parameter the join method takes is a separator. In this example we provide an empty string as the separator and join the array elements without the commas.
console.log(['one', 'two'].join('')); // ๐Ÿ‘‰๏ธ 'onetwo'

The join method returns a string with all of the array elements separated by the provided separator.

If you call the join method with an empty string, all array elements get joined without any characters in between them.

Similarly, if we need to separate the array elements when joining them into a string, we can pass a different parameter to the join method.

console.log(['one', 'two'].join('-')); // ๐Ÿ‘‰๏ธ 'one-two' console.log(['one', 'two'].join(' ')); // ๐Ÿ‘‰๏ธ 'one two'

In our first example, we join the array elements with a hyphen - and in our second example, we pass a string containing a space to join the elements with a space.

You can also use the JSON.stringify method to convert an array to a string.

const stringified = JSON.stringify(arr); console.log(stringified); // ๐Ÿ‘‰๏ธ '["one", "two", "three"]' console.log(typeof stringified); // ๐Ÿ‘‰๏ธ string

The JSON.stringify() method takes a value and converts it to a JSON string.

This method is more likely to be used when sending data via an HTTP request, than when performing operations in your application code.

The most flexible way to convert an array to a string is to use the Array.join method and provide the separator that suits your use case.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee