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

Topic: JavaScript / jQuery« Prev|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 (,).

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="UTF-8">
  • <title>jQuery Create String from Array Elements</title>
  • <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
  • <script type="text/javascript">
  •     $(document).ready(function(){
  •         var superheros = ["Superman", "Hulk", "Spiderman"];
  •         var fight = superheros.join("-vs-");
  •         $("input[type='button']").click(function(){
  •             alert(fight);
  •         });
  •     });
  • </script>
  • </head> 
  • <body>
  •     <p><input type="button" value="Fight List"></p>
  •     <p>Click the above button to know the fight list.</p>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.