You might find yourself needing to convert an array into a string in JavaScript, for a number of reasons.
In this post we will cover how to convert an array into a string with commas, without commas, and how to convert an array of objects into a string in JavaScript as well.
It is actually really simple and easy to be able to do, so let’s get stuck in.
Which method converts an array to string in JavaScript
There are two methods we can use to convert an array to string in JavaScript, either the Array.prototype.toString method, or the Array.prototype.join method.
Using toString keeps things nice and simple, but using the join method gives us much more control.
Let’s take a look at how we can convert an Array into a String in JavaScript.
How to convert an Array into a String in JavaScript
Firstly we are going to look at how we can convert an array to a string in javascript with commas using Array.prototype.toString and Array.prototype.join.
[1, 2, 3, 4, 5].toString() // "1,2,3,4,5"
[1, 2, 3, 4, 5].join() // "1,2,3,4,5"
As you can see both of these methods convert the array into a string with commas.
How to convert an Array into a String in JavaScript without commas
To convert an array to a string in JavaScript without commas, we need to use the Array.prototype.join method because it can allow us to provide an argument to say how we want our string to be.
If you want to convert the array into a string without commas, and instead with spaces then all you need to do is pass a space into the Array.prototype.join method.
Here is an example of how to convert an Array into a String in JavaScript without commas using the join method:
[1, 2, 3, 4, 5].join(" ") // "1 2 3 4 5"
[1, 2, 3, 4, 5].join("-") // "1-2-3-4-5"
How to convert an array of objects to a string in JavaScript
When converting an array of objects into a string in JavaScript, it is a little different in comparison with simple arrays, but equally as easy.
Instead of using Array.prototype.toString, or Array.prototype.join, we instead need to use a function called JSON.stringify.
This function will convert any JavaScript object or array into a string version of it that can be saved as JSON data.
Here is how to use JSON.stringify to convert an array of objects to a string in JavaScript:
JSON.stringify([{ apples: 10 }, { apples: 15 }]) // '[{"apples":10}, {"apples":15}]'
Summary
There we have how to convert an Array into a String in JavaScript, if you want more like this be sure to check out some of my other posts!