Unfortunately for us, the methods to turn arrays to strings and strings to arrays are not named that explicitly, but here is a quick cheat sheet on how to do it.
Array to String
Let’s say we have an array of fruits:
let fruitsArray = ['strawberries', 'bananas', 'apples'];
To make it an array, we have 2 options: toString()
and join()
.
let fruitsJoin = fruitsArray.join(); console.log("fruitsJoin: %o", fruitsJoin); // returns: strawberries,bananas,apples let fruitsJoinDash = fruitsArray.join(" - "); console.log("fruitsJoinDash: %o", fruitsJoinDash); // returns: strawberries - bananas - apples let fruitsToString = fruitsArray.toString(); console.log("fruitsToString: %o", fruitsToString); // returns: strawberries,bananas,apples
We can see in this example that join()
without parameter is equivalent to toString()
. For more flexibility, I prefer using join()
to specify the separator I want (by default, it’s: ","
).
Have a look at the documentation for more details about join() and toString().
String to Array
Let’s say we have now a vegetables string:
let vegetablesString = "potatoes, broccoli, carrots";
Now, to make it into an array, all we need to do is to split it!
let vegetablesSplit = vegetablesString.split(", "); console.log("vegetablesSplit: %o", vegetablesSplit); // returns: ["potatoes","broccoli","carrots"] let vegetablesSplitDefault = vegetablesString.split(); console.log("vegetablesSplitDefault: %o", vegetablesSplitDefault); // returns: ["potatoes, broccoli, carrots"] let vegetablesSplitLimit = vegetablesString.split(", ", 2); console.log("vegetablesSplitLimit: %o", vegetablesSplitLimit); // returns: ["potatoes","broccoli"]
The split()
method takes 2 optional parameters: the separator and the limit. Please note that if you don’t specify the separator, split()
will return an array containing the entire original string. Also, the limit, as its name states, will limit the number of elements returned in the array.
Have a look at the documentation for more details about split().
👉As always, you can find all the examples above (and play with them) in the dedicated Codepen: JS Array to String and String to Array.
Feel free to buy me a coffee (or tea) if you found this article useful ☕️ 🙂