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

76,024

Solution 1

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

Solution 2

pass a delimiter in to join.

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

Solution 3

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

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

Share:
76,024
tlaminator
Author by

tlaminator

software engineer interested in data

Updated on September 01, 2021

Comments

  • tlaminator
    tlaminator over 2 years

    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
    
  • David
    David over 8 years
    its amazing how many times console.log() makes you realize a function doesn't do exactly what you expect...
  • Eric Ong
    Eric Ong over 5 years
    is there a way to display [apple] [tree] instead?
  • Zeeshan Safdar
    Zeeshan Safdar over 3 years
    What if we just do array.join(''). So there is no need to trim.