Javascript - Convert array to String (with and without commas)
Short article to convert array to string with commas and without commas using join method.
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
Related Posts
Press Shift + Enter for new Line in Textarea
Override default textarea behavior on Enter key press without Shift, prevent new lines, and take custom actions like submitting forms instead. Still allow Shift+Enter newlines.
in vs hasOwnProperty(): Differences in Inherited Properties
The article explains the differences between JavaScript's 'in' operator and 'hasOwnProperty()' method. And also learn the use cases of both in JS.
How to Fix "ReferenceError: document is not defined" in JavaScript
The "ReferenceError: document is not defined" is a common error in JavaScript that occurs when trying to access the `document` object in a non-browser environment like Node.js.
How to Fix the "Cannot Read Property of Undefined" Error in JavaScript
The "Cannot read property of undefined" error occurs when you try to access a property or method of a variable that is undefined in JavaScript.
