Join an array by a comma and a space

Myles Gray picture Myles Gray · Feb 22, 2011 · Viewed 64.2k times · Source

I have an array that I want converted to a comma delimited string. Array.toString() works, but if I have a rather large array it won't wrap because there are no spaces after the commas:

How can I have spaces after the commas in order to allow line/word wrapping?

Example output:

css, html, xhtml, html5, css3, javascript, jquery, lesscss, arrays, wordpress, facebook, fbml, table, .htaccess, php, c, .net, c#, java

Answer

Nick Craver picture Nick Craver · Feb 22, 2011

In JavaScript there's a .join() method on arrays to get a string, which you can provide the delimiter to. In your case it'd look like this:

var myArray = ['css','html','xhtml','html5','css3','javascript','jquery','lesscss','arrays','wordpress','facebook','fbml','table','.htaccess','php','c','.net','c#','java'];
var myString = myArray.join(', ');

You can test it out here