Javascript – Convert array to String (with and without commas)

In this article, we will learn how to convert an array into a string with and without commas.

In Javascript, we can convert an array into a string using the in-built method called the join() method. We have to call the join() method on the array to convert and it will return us a string containing the array items.

Convert array to String in Javascript

The join() method is used to return an array as a string in Javascript.

Syntax:

array.join(separator)

The separator is optional character that is used to separate elements of an array.

If not specified, it will use a comma (,) as the default value.

let arr = ['hello','how','are','you']

let str = arr.join()

console.log(str)

Output:

hello,how,are,you

Here, we have converted the array into a string using join() method. And since we have not passed any separator, it returns the string with commas.

Now let’s see how to get the string without the commas.

Convert array to string without commas

Now, to convert the array into a string without the commas, we can just pass an empty string in the join() method.

Example:

let arr = ['hello','how','are','you']

let str = arr.join(' ')

console.log(str)

Output:

hello how are you

Since we have passed an empty string (' ') as a parameter in the join method, it will print out empty spaces instead of commas.

That’s how we get a string without commas.

If you want other characters instead of commas or spaces, you can see the example below.

let str = arr.join('-') // hello-how-are-you
let str = arr.join(', ') // hello, how, are, you

As you can see, we can use any character as a separator in the join method.

Here, in the first line, we have used a dash (-) as a separator and in the second line, we have used commas and spaces together(‘,‘) to print it out with the string.


Other Articles You’ll Also Like:

Convert array to string with brackets and quotes in JavaScript

Split a String into chunks of N character into an array in JavaScript

How to convert an array to object in javascript?

Convert javascript array to object of same keys/values

Compare Elements of Two Arrays in JavaScript

Scroll to Top