JavaScript Array Join

Created with Sketch.

JavaScript Array Join

Summary: in this tutorial, you’ll learn how to use the JavaScript Array join() method to concatenate all elements of an array into a string separated by a separator.

Introduction to the JavaScript array join() method

The join() method allows you to concatenate all elements of an array and returns a new string:

Array.prototype.join([separator])

Code language: CSS (css)

The join() method accepts a optional argument separator which is a string that separates each pair of adjacent elements of the array in the result string.

The separator defaults to a comma if you don’t pass it to the join() method.

In case the array has one element, the join() method returns that element as a string without using the separator.

And if the array is empty, the join() method returns an empty string.

When the elements of the array aren’t strings, the join() method converts them to strings before joining.

Note that the join() method converts undefined, null, and empty array [] to an empty string.

JavaScript Array join() method examples

Let’s take some examples of using the join() method.

1) Using the JavaScript Array join() method to join CSS classes

The following example uses the JavaScript Array join() method to join CSS classes:

const cssClasses = ['btn', 'btn-primary', 'btn-active'];
const btnClass = cssClasses.join(' ');

console.log(btnClass);

Code language: JavaScript (javascript)

Output:

btn btn-primary btn-active

 

In this example, we have an array that holds a list of CSS classes. And we use the join() method joins all elements of the cssClasses array and return a string of the CSS classes separated by a space.

2) Using the JavaScript Array join() method to replace all occurrences of a string

This example uses the JavaScript Array join() method to replace all occurrences of the space ' ' by the hyphen (-):

const title = 'JavaScript array join example';
const url = title.split(' ')
.join('-')
.toLowerCase();

console.log(url);

Code language: JavaScript (javascript)

Output:

javascript-array-join-example

Code language: PHP (php)

How it works:

  • First, split the title string by the space into an array by using the split() string method.
  • Second, concatenate all elements in the result array into a string by using the join() method.
  • Third, convert the result string to lower case by using the toLowerCase() method.

Summary

  • Use the JavaScript Array join() method to concatenate all elements of an array into a string separated by a separator.

Leave a Reply

Your email address will not be published. Required fields are marked *