Skip to content

Convert JavaScript array to string | toSrting and join method examples

  • by

How to Convert JavaScript array to string?

Using the toString() or join() method you can easily Convert JavaScript array to string. The elements will be separated by a specified separator. It’s up to you to choose any separator in a string or not.

Note: Using this methods will not change the original (given) array.

Examples of the JavaScript array to string

Let’s see the examples of Array to string in JS using different ways and methods.

Using toString() Method

Converting the elements of an array into a string with comma separate.

array.toString()

You don’t have to pass comma to get comma separate string from Array.

<!DOCTYPE html>
<html>
  <head>
    <script>

    	var alpha = ["A", "B", "C", "D"];
		var beta = alpha.toString();

		console.log( beta );

    </script>
  </head>   

</html>

Output:

Convert JavaScript array to string toSrting method

Using join() Method

The elements will be separated default separator comma (,).

array.join(separator)

Example

<!DOCTYPE html>
<html>
  <head>
    <script>

    	var alpha = ["B", "A", "M", "D"];
		var beta = alpha.join();

		console.log( beta );

    </script>
  </head>   

</html>

Output:

Convert JavaScript array to string join

Q: How to convert JavaScript array to string without commas?

Answer: When you call join without any argument being passed, ,(comma) is taken as default and toString internally calls join without any argument being passed.

So, pass your own separator. Here we are passing a space.

<script>

    	var alpha = ["B", "A", "M", "D"];
	var str = alpha.join(' ');

        console.log( str );

</script>

Output: B A M D

Q: How to JavaScript array to string with spaces?

Answer: In JavaScript, there’s a .join() method on arrays to get a string, which you can provide the delimiter to. In your case it’d look like this:

<!DOCTYPE html>
<html>
  <head>
    <script>

    	var alpha = ["B", "A", "M", "D"];
		var myString = alpha.join(', ');

		console.log( myString );

    </script>
  </head>   

</html>

Output: B, A, M, D

Do comment if you have any doubts and suggestion on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

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