Suppose you have an array and, for one reason or another related to your app’s frontend or backend, you want to convert that array to a string without commas.
What is the best way to do that?
To convert an array into a string without commas, call the Array.join(separator)
method and give it an empty string, with two quotation marks and nothing between them, as the separator
argument.
The Array.join()
method takes an array and returns a string with its concatenated elements.
Its syntax is as follows:
// Syntax
Array.join(separator);
The separator
argument is optional (that said, it’s also the key to solving this challenge). It is a string to separate every pair of adjacent elements in your array.
If you don’t specify a separator
argument, the Array.join()
method will return a string with comma-separated elements:
// Declare myArray with values of 1, 2, 3, 4, 5
var myArray = [1, 2, 3, 4, 5];
// Redeclare myArray as a string
var myArray = myArray.join();
// Output result to console
console.log(myArray); // 1,2,3,4,5
Specify an empty string (''
) as a separator, and the method returns a commaless concatenated string:
// Declare myArray with values of 1, 2, 3, 4, 5
var myArray = [1, 2, 3, 4, 5];
// Redeclare myArray as a string
var myArray = myArray.join('');
// Output result to console
console.log(myArray); // 12345
You could, of course, specify blank space (' ')
as a separator to have the method return a string with elements separated by a blank space:
// Declare myArray with values of 1, 2, 3, 4, 5
var myArray = [1, 2, 3, 4, 5];
// Redeclare myArray as a string
var myArray = myArray.join(' ');
// Output result to console
console.log(myArray); // 1 2 3 4 5
In Conclusion
Converting an array into a string without commas is easy to do in JavaScript. All you have to do is call the Array.join()
method with an empty string or blank space as a separator
argument.