How to Convert JavaScript array into comma separated string

In this JavaScript tutorial, we gonna learn how to convert JavaScript array into comma separated string. JavaScript is now becoming the more popular day by day and thus the developers are somehow making them good in JavaScript. In this post, the JavaScript developers gonna learn a good practical task that might be used in various projects from a small one to a big one.

In many situations, we get an array holding a lot of elements. Sometimes we need to work with those array elements.
Today we will learn one of those works. We gonna convert a JavaScript array into comma separated string. That means we will create a string from a JavaScript array. Also, we will separate each element with a comma. The newly created string will be known as comma separated string. So, are you ready for this?

How to convert JSON array to normal Java Array Easily

Convert JavaScript array into comma separated string

Now, we will create a JavaScript array with some elements. Our aim is to create a string which will hold the elements in a single string. Each element will be separated with a comma in that string.

So, let’s create our JavaScript array.

var my_array=['PHP','Java','JavaScript','C++'];

Now we are going to print it as comma separated string.

document.write(my_array.toString());

It will give you the desired result.

full example:

<!DOCTYPE html>
<html>
<head>
  <title>Title Goes Here</title>
</head>
<body>
  <script type="text/javascript">
    var my_array=['PHP','Java','JavaScript','C++'];
    document.write(my_array.toString());
  </script>
</body>
</html>

Output:

PHP,Java,JavaScript,C++

.toString() actually calls the .join() so it will join the elements with commas.

So you can also use the below:

<script type="text/javascript">
	var my_array=['PHP','Java','JavaScript','C++'];
	document.write(my_array.join());
</script>

here the output will be like this:

PHP,Java,JavaScript,C++

So, this is the same as the previous one. But you can add something after comma here. Or you can add a space by just doing the following:

document.write(my_array.join(", "));

Output:

PHP, Java, JavaScript, C++

Finally, If you have any query or doubts related to JavaScript array to comma separated string simply comment in the comment section provided below.

Also read,

How to unset a JavaScript variable?

How to convert binary to decimal in JavaScript easily

Leave a Reply

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