In this tutorial, we are going to check how to convert a JavaScript array to a string with or without commas.
In order to convert an array into a string, we can use the toString()
built-in method that will return all array elements in a comma-separated string.
CONTENTS
JavaScript array to string with commas
Let’s check an example first.
let javascript_array = ['Array', 'To', 'String'];
let array_to_string = javascript_array.toString();
console.log(array_to_string);
// output will be "Array,To,String"
JavaScript array to string without commas
Sometimes we need a string where comma-separated values are not required. But we can’t pass any argument to the toString()
method to generate without a comma-separated string from an array.
In this case, we can use the .join()
method. If we call this method without any argument, it will return the same output as toString()
.
toString()
method call join()
method internally without pass any argument. You can pass any separator to join()
.
console.log( ['Array', 'To', 'String'].join() );
// "Array,To,String"
console.log( ['Array', 'To', 'String'].join(' ') );
// "Array To String"
console.log( ['Array', 'To', 'String'].join('') );
// "ArrayToString"
console.log( ['Array', 'To', 'String'].join('|') );
// "Array|To|String"
Array to string with brackets and quotes
let javascript_array = ['Array', 'To', 'String'];
let array_to_string = JSON.stringify(javascript_array);
console.log(array_to_string);
//output "[\"Array\",\"To\",\"String\"]"