To convert an array into a string without commas in JavaScript, you can use the Array.join()
method. The Array.join()
method joins the array elements with the specified separator string and returns a new string containing all array elements joined with the separator.
So, to convert the array into a string without commas, you can simply pass a blank string('')
as a parameter to the join()
method. This will return you a string containing all array elements joined without commas.
See the following example:
const arr = ['a', 'b', 'c', 'd', 'e']; const str = arr.join(''); console.log(str); // Output: 'abcde' console.log(typeof str); // Output: string
If your requirement is to convert the array into a string with spaces, you can simply pass a separtor string that contains a space as a parameter to the join()
method. This will return you a string that joins array elements with spaces.
See the following example:
const arr = ['a', 'b', 'c', 'd', 'e']; const str = arr.join(' '); console.log(str); // Output: 'a b c d e'
If you do not pass any parameter to the join()
method, it will convert the array into a comma-separated(without space) string.
See this example:
const arr = ['a', 'b', 'c', 'd', 'e']; const str = arr.join(); console.log(str); // Output: 'a,b,c,d,e'
The join()
method gives you full control to separate the array elements with any string that you want. This means you can simply generate strings with space-separated, comma-separated, hyphen-separated, and so on.
See the following example:
const arr = ['a', 'b', 'c', 'd', 'e']; const withCommas = arr.join(', '); console.log(withCommas); // Output: 'a, b, c, d, e' const withHyphens = arr.join('-'); console.log(withHyphens); // Output: 'a-b-c-d-e'
If the array contains values like null
and undefined
, they are simply converted to empty strings while joining.
This means if we join such values with empty strings('')
then these values will be simply ignored and will not be part of the final string.
See this example:
const arr = ['a', undefined, null, 'b']; const str = arr.join(''); console.log(str); // Output: 'ab' const str2 = arr.join('-'); console.log(str2); // Output: 'a---b'