In JavaScript, arrays are an effective data structure that you can use to store and manage collections of values. Nevertheless, there are some circumstances in which you might need to convert an array into a string, such as when you want to display the contents of the array on a web page or send the array as a parameter in a URL.
Mainly it is done by traversing on the Array and concat value to a variable with a separator for string conversion.
Fortunately, there are several built-in methods in JavaScript that can be used to convert an array to a string.
Contents
1. Using Loop add a separator
Traverse through an Array until the variable value is less than Array length and concatenate array value to a string variable.
Example
<script type='text/javascript'> // Array var num_arr = [23,1,65,90,34,21]; // Array length var arr_len = num_arr.length; var num_str = ''; // Traverse for(var i=0;i< arr_len; i++){ // Concat Array value to string variable num_str += num_arr[i]; // Add separtor if(i < (arr_len-1) ){ num_str += ','; } } console.log( num_str ); </script>
Output
23,1,65,90,34,21
2. Use the toString()
This converts an Array to string and returns a comma-separated value.
Note – Its default separator is the comma(,) and it doesn’t allow to specify separator.
Syntax –
Array.toString();
Example
<script type='text/javascript'> // Array var names_arr = ['Yogesh','Sonarika','Vishal','Aditya']; // Array conversion var names_str = names_arr.toString(); console.log( names_str ); </script>
Output
Yogesh,Sonarika,Vishal,Aditya
3. Use the join()
It also converts an Array to String and allows to specify separator. Its default separator is the comma(,).
Syntax –
Array.join();
Or
Array.join( separator );
Example
<script type='text/javascript'> // Array var names_arr = ['Yogesh','Sonarika','Vishal','Aditya']; // Array conversion var names_str = names_arr.join(' - '); console.log('names : ' + names_str); </script>
Output
Yogesh - Sonarika - Vishal - Aditya
4. Conclusion
I showed how you can convert an Array to string with Loop and inbuilt JavaScript methods. You can use the inbuilt methods for one-line conversion.
If you want to execute some code while conversion then use Loop e.g. check Array value before concatenating.
If you found this tutorial helpful then don't forget to share.