Borislav Hadzhiev
Wed Oct 20 2021·2 min read
Photo by Alex Wong
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.
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.
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.
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.