Convert Array to String by JavaScript toString and join (4 Demos)

How to convert an array to string in JavaScript?

JavaScript has a few built-in methods to convert an array to string. These are toString and join methods. Both these methods are explained in this tutorial with examples.

The toString method

The toString method is used to convert a JavaScript array to string and returns the string representation of that array. The array values are separated by commas after converting into the string.

Following is an example of using toString JavaScript method, let us first look at its syntax.

Syntax of JavaScript toString

The syntax to use toString method is:

Array_name.toString();

The letter ‘S’ in toString must be capital.

An array to string example

Following is an example of converting JavaScript array to string. We have created an array of four US State names. Then we will use JavaScript toString method to convert that array into the string.

As you press the button, the HTML paragraph will be filled by converted string. See the example by clicking the link or image below:

JavaScript toString

Experience this example online



An example of toString for a numeric array

The following example will convert a numeric array to string by using JS toString method. See the example online by clicking the link below:

Experience this example online



The join method

The join method ‘joins’ all elements of an array into a string by a given separator. If no separator is given (as a parameter) in JS join method, a comma will be used to join elements of the array into the string.

Following are a few examples of using JavaScript join method but let us first look at its syntax.

Syntax of array join method

Following is the general syntax of using array join method:

Array_name.join(separator);

Where separator will be placed between array elements. The default separator is a comma.

A join array example

Following is an example of using JavaScript join array method. We have created an array of four elements. As you press the button, the returned string will be displayed in HTML paragraph after using join method.

Experience this example online



You saw the array merged by using join method. As such no separator was given, elements are separated by commas.

JavaScript join example with a separator

This example uses pipe sign (|) as a separator between array elements while using join array method. The returned string is then displayed in HTML paragraph.

JavaScript Join

Experience this example online



You can see array elements are separated by (|) sign after using the join method.


Was this article helpful?

Related Articles

Leave A Comment?