I know you can do this through looping through elements of array and concatenating. But I'm looking for one-liner solutions. toString() and join() returns string with elements separated by commas. For example,
var array = ['apple', 'tree']; var toString = array.toString()    # Will return 'apple,tree' instead of 'apple tree', same for join() method 
                To convert an array to a string without commas, call the join() method on the array, passing it an empty string as a parameter - arr. join('') . The join method returns a string containing all array elements joined by the provided separator. Copied!
To convert an array to a string with spaces, call the join() method on the array, passing it a string containing a space as a parameter - arr. join(' ') . The join method returns a string with all array elements joined by the provided separator.
Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.
join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
pass a delimiter in to join.
['apple', 'tree'].join(' '); // 'apple tree' 
                        When you call join without any argument being passed, ,(comma) is taken as default and toString internally calls join without any argument being passed.
So, pass your own separator.
var str = array.join(' '); //'apple tree' // separator ---------^   MDN on Array.join
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With