Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array into comma separated string in javascript [duplicate]

I have an array

a.value = [a,b,c,d,e,f]

How can I convert to comma seperated string like

a.value = "a,b,c,d,e,f"

Thanks for all help.

like image 862
David Avatar asked Sep 29 '16 13:09

David


People also ask

How do you convert an array to a comma with strings?

To convert an array to a comma-separated string, call the join() method on the array, passing it a string containing a comma as a parameter. The join method returns a string containing all array elements joined by the provided separator.

How do you store comma separated values in an array?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.

How Split comma separated Values in HTML?

To convert comma separated text into separate lines, you need to use trim() along with split() on the basis of comma(,).

How do you turn a string into an array in JavaScript?

The string in JavaScript can be converted into a character array by using the split() and Array. from() functions.


2 Answers

The method array.toString() actually calls array.join() which result in a string concatenated by commas. ref

var array = ['a','b','c','d','e','f'];
document.write(array.toString()); // "a,b,c,d,e,f"

Also, you can implicitly call Array.toString() by making javascript coerce the Array to an string, like:

//will implicitly call array.toString()
str = ""+array;
str = `${array}`;

Array.prototype.join()

The join() method joins all elements of an array into a string.

Arguments:

It accepts a separator as argument, but the default is already a comma ,

str = arr.join([separator = ','])

Examples:

var array = ['A', 'B', 'C'];
var myVar1 = array.join();      // 'A,B,C'
var myVar2 = array.join(', ');  // 'A, B, C'
var myVar3 = array.join(' + '); // 'A + B + C'
var myVar4 = array.join('');    // 'ABC'

Note:

If any element of the array is undefined or null , it is treated as an empty string.

Browser support:

It is available pretty much everywhere today, since IE 5.5 (1999~2000).

References

  • ECMA Specification
  • Mozilla
  • MSDN
like image 133
Vitim.us Avatar answered Oct 16 '22 09:10

Vitim.us


Use the join method from the Array type.

a.value = [a, b, c, d, e, f];
var stringValueYouWant = a.join();

The join method will return a string that is the concatenation of all the array elements. It will use the first parameter you pass as a separator - if you don't use one, it will use the default separator, which is the comma.

like image 32
Geeky Guy Avatar answered Oct 16 '22 08:10

Geeky Guy