Join Elements of String Array with Delimiter String

To join elements of a string array with given delimiter string as separator in JavaScript, call join() method on the string array and pass the delimiter string as argument in the method call.

The expression to join elements of a string array arr by a delimiter string separator is

</>
Copy
arr.join(separator);

Examples

In the following example, we take a string array in arr, join the elements in the array with delimiter string ' - ' as separator, and display the resulting string in pre#output.

index.html

<!DOCTYPE html>
<html lang="en">
  <body>
    <pre id="output">Output : </pre>
    <script>
      var arr = ['apple', 'banana', 'cherry'];
      var strOutput = arr.join(' - ');
      document.getElementById('output').innerHTML += strOutput;
    </script>
  </body>
</html>

In the following example, we join the elements of string array arr with delimiter string '++++' as separator, and display the resulting string in pre#output.

index.html

<!DOCTYPE html>
<html lang="en">
  <body>
    <pre id="output">Output : </pre>
    <script>
      var arr = ['apple', 'banana', 'cherry'];
      var strOutput = arr.join('++++');
      document.getElementById('output').innerHTML += strOutput;
    </script>
  </body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to join the elements of a string array with given separator string using Array.join() method, with example program.