Array to String in JavaScript

Convert a JavaScript Array into String with or without commas.

As a developer using JavaScript, you will certainly need to turn strings into an array. Let me show you how to do it using the Array built-in join method.

This method allows you to convert a simple array to a string.

Note: It will not work with the array of objects.

Split String by comma into an Array

By default, the join method uses the comma as a separator. If you convert your array to a string, you will have:

const myArray = ['Hello', 'everyone', 'how', 'are', 'you', '?']

const myString = myArray.join()

console.log(myString)
// Output: 'Hello,everyone,how,are,you,?'

Array to String using the toString method

One other way to split your array into a string is by using the built-in toString method. The result is the same.

const myArray = ['Another', 'example', 'using', 'the', 'toString', 'method']

console.log(myArray.toString())
// Output: 'Another,example,using,the,toString,method'

// OR
// Note: not explicit, `toString` is recommended
console.log(myArray + '')
// Output: 'Another,example,using,the,toString,method'

Convert Array to String without comma

If you want to split an array into a string using a separator, you can add a parameter to the join method.

Your separator can be a single character or a string. It will replace the default comma separator.

Here is an example with a space character:

const myArray = ['Hello', 'there', 'is', 'a', 'space', 'separator']

const myString = myArray.join(' ')

console.log(myString)
// Output: 'Hello there is a space separator'

If you only want to convert your array to a string without any separator nor comma, you can set an empty string as a parameter:

const myArray = ['Hello', 'there', 'is', 'no', 'separator']

const myString = myArray.join('')

console.log(myString)
// Output: 'Hellothereisnoseparator'

➡️ I help web developers improve their skills 💻 If you want to get more tips and resources about web programming -> Follow me on Twitter 🐦

Learn to code with simple and concrete examples.

English / Français