In JavaScript, we can convert an array of elements into to string without commas easily using the Array join() method.

var arrayOfColors = ["Red", "Green", "Blue", "Orange", "Yellow"];
var stringOfColors = arrayOfColors.join(" ");

The join method will convert an array of values into a string for us just using the join() method as is. This will create a string with the value of the array in it separated by commas. If we want to get rid of the commas, and just have the value separated by spaces, we would use the code above, arrayOfColors.join(” “);.

Let’s take a look at a simple example below.


Let’s say we have a simple array of colors and we want to convert the array to a string without commas. To do this we simply need to use the JavaScript Array join() method.

var arrayOfColors = ["red","blue","green","yellow","orange","purple","pink","black"];
var stringOfColors = arrayOfColors.join(" ");

In this example, the resulting string “stringOfColors” would now contain the following:

red blue green yellow orange purple pink black

Let’s take a look at an example using HTML.

Converting an Array of Values into a String Without Commas with a Click

In this example, we will have a large array with the elements each containing a string. We will take the long array of text, and convert it into one long string, and then show it to the user.

Here is the HTML set up:

Show text

In the JavaScript portion of this example, all we will do is grab the array of text that we created, and use the join() method on it to convert it into a string. We will then show the string to the user using the textContent property.

The text we will use in our array will just be text we take from our about page.

Here is the JavaScript code:

var aboutText = ["This", "blog", "is", "a", "compilation", "of", "a", "programmer’s", "findings", "in", "the", "world", "of", "software", "development", ", website", "creation,", "and", "automation", "of", "processes."];

function showText() {
  //Convert our array of text above into a string with each item of the array separated by a space.
  var newText = aboutText.join(" ");
  //Show text to the user
  document.getElementById("results").textContent = newText;
};

The final code and output for this example is below:

Code Output:

Show text

Full Code:

Show text



Hopefully this article has been useful for you to understand how to use JavaScript to convert an array to string without commas.

Read more here.

Categorized in:

JavaScript,

Last Update: May 3, 2024