Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array into string without comma and separated by space in javascript without concatenation?

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 
like image 915
tlaminator Avatar asked Jan 18 '15 07:01

tlaminator


People also ask

How do I convert an array to a string without commas?

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!

How do I turn an array into a string with spaces?

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.

How can I convert a comma separated string to an array JavaScript?

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.

How do I join JavaScript?

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.


2 Answers

pass a delimiter in to join.

['apple', 'tree'].join(' '); // 'apple tree' 
like image 38
Cheezmeister Avatar answered Sep 22 '22 19:09

Cheezmeister


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

like image 196
Amit Joki Avatar answered Sep 24 '22 19:09

Amit Joki