In this article, we will learn how to convert an array into a string with and without commas.
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.
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)
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
let arr = ['hello','how','are','you'] let str = arr.join(' ') console.log(str)
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
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: