How To Convert Array to Comma Separated String JavaScript?

01-May-2023

.

Admin

How To Convert Array to Comma Separated String JavaScript?

This post is focused on how to convert array into comma separated string in javascript. We will use how to convert array into comma separated string in javascript. I explained simply step by step create a comma separated list from an array in javascript. This article goes in detailed on convert array to comma separated string javascript.

There are several ways to convert an array to a comma-separated string in JavaScript:

1. Using the join() method: The join() method joins all elements of an array into a string, separated by a specified separator (in this case, a comma).

Example 1:


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How To Convert Array to Comma Separated String JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

const arr = [1, 2, 3];

const str = arr.join(',');

console.log(str); // Output: "1,2,3"

</script>

</html>

2. Using the toString() method: The toString() method converts an array to a string by concatenating all its elements separated by commas.

Example 2:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How To Convert Array to Comma Separated String JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

const arr = [1, 2, 3];

const str = arr.toString();

console.log(str); // Output: "1,2,3"

</script>

</html>

3. Using a loop: You can also use a for loop to iterate over the array and concatenate its elements with commas.

Example 3:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How To Convert Array to Comma Separated String JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

const arr = [1, 2, 3];

let str = '';

for (let i = 0; i < arr.length; i++) {

if (i === arr.length - 1) {

str += arr[i];

} else {

str += arr[i] + ',';

}

}

console.log(str); // Output: "1,2,3"

</script>

</html>

#JavaScript