tlaminator
tlaminator

Reputation: 1006

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

Upvotes: 46

Views: 94180

Answers (6)

rachidFront Dev
rachidFront Dev

Reputation: 41

You could use splice method to add space item to array

var array = ['apple', 'tree'];
 array.splice(1, 0, ' ')

And for convert array to string use built-in methode call join()and the output will be like you want:

array.join('');
// "apple tree"

Upvotes: 0

Tiernan Crotty
Tiernan Crotty

Reputation: 307

If you didn't want to use toString() or join(), you could do something like this:

for(let i=0;i</*Array*/.length;i++)if(/*Variable*/=="")/*Variable*/+=/*Array*/[i];else /*Variable*/+="/*Separator*/"+/*Array*/[i];

Separator is what to put between each item. In your case, you would change that to a space.

Upvotes: 0

Seyi Oluwadare
Seyi Oluwadare

Reputation: 171

Use the Array.join() method. Trim to remove any unnecessary whitespaces.

var newStr = array.join(' ').trim()

Upvotes: 4

Richie Bendall
Richie Bendall

Reputation: 9172

The easiest way is to use .join(' ').

However, if the Array contains zero-length objects like null, the following code would avoid multiple spaces:

arr.filter(i => [i].join(" ").length > 0).join(" ");

Here's some example usage:

Array.prototype.merge = function(char = " ") {
  return this.filter(i => [i].join(" ").length > 0).join(char);
};

console.log(["a", null, null, "b"].merge());

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59232

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

Upvotes: 89

Cheezmeister
Cheezmeister

Reputation: 4985

pass a delimiter in to join.

['apple', 'tree'].join(' '); // 'apple tree'

Upvotes: 5

Related Questions