WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES

How to create a string by joining the elements of an array in JavaScript

Topic: JavaScript / jQueryPrev|Next

Answer: Use the JavaScript join() method

You can easily create a string by joining the elements of an array using the JavaScript join() method. The join() method also allow you to specify seperator to seperate the array elements. The default separator is comma (,). Here's an example:

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="UTF-8">
  • <title>JavaScript Create String by Joining Array Elements</title>
  • </head> 
  • <body>
  •     <script>
  •         // Sample array
  •         var colors = ["red", "green", "blue"];
  •         
  •         // Joining array elements
  •         alert(colors.join()); // Outputs: red,green,blue
  •         alert(colors.join(", ")); // Outputs: red, green, blue
  •         alert(colors.join("-")); // Outputs: red-green-blue
  •         alert(colors.join(" + ")); // Outputs: red + green + blue
  •         alert(colors.join("")); // Outputs: redgreenblue
  •     </script>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

Your Feedback:

We would love to hear from you, please drop us a line.