Urbycoz
Urbycoz

Reputation: 7421

Create comma-delimited string

I'm looking to find a neat way to create a comma-delimited string from an array. This is how I'm doing it now...

for(i=0;i<10;i++)
{
   str = str + ',' + arr[i];
}
str=str.substring(1)
return str;

... but it feels a bit untidy.

Upvotes: 41

Views: 50713

Answers (5)

Oliver M Grech
Oliver M Grech

Reputation: 3171

you have to use

var joinedstr = myarray.join(',');

Upvotes: 2

Alex
Alex

Reputation: 7374

Use the join function:

myarray.join(',');

Upvotes: 1

Sachin Shanbhag
Sachin Shanbhag

Reputation: 55489

I think there is something like array.join(',') where array is your array variable instance.

Upvotes: 1

mbq
mbq

Reputation: 18628

Use the join method:

arr.join(',');

Upvotes: 2

jAndy
jAndy

Reputation: 236022

Array.prototype.join() is what you're looking for:

arr.join(',');

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/join


var arr = ['Hi', 'I', 'am', 'a', 'comma', 'separated', 'list'];

arr.join(',');  // === "Hi,I,am,a,comma,separated,list" 

Upvotes: 72

Related Questions