92

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:

document.body.innerHTML = ['css','html','xhtml','html5','css3','javascript','jquery','lesscss','arrays','wordpress','facebook','fbml','table','.htaccess','php','c','.net','c#','java'].toString();
// css,html,xhtml,html5,css3,javascript,jquery,lesscss,arrays,wordpress,facebook,fbml,table,.htaccess,php,c,.net,c#,java

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
Myles Gray
  • 8,711
  • 7
  • 48
  • 70
  • Related: http://stackoverflow.com/questions/5289403/jquery-convert-javascript-array-to-string/12810028#12810028 – Justin Feb 18 '14 at 18:28

5 Answers5

200

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

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
26

Use array.join(", "); and it should work

adarshr
  • 61,315
  • 23
  • 138
  • 167
2
 string.Join(", ", new string[] { "css", "html", "xhtml", ..etc });

This prints the items with a comma and a space

[edit] I'm sorry, did not see it was for javascript. My code is c# :)

John xyz
  • 176
  • 5
0

Try this way by the regex

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

let myString = arr.replace(/,[s]*/g, ", ");


console.log(myString);
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
Force Bolt
  • 1,117
  • 9
  • 9
0

I saw in a comment the question of how to make that without the .join() function.

Here is one tricky way:

const array_of_strings = ['css','html','xhtml','html5','css3','javascript','jquery','lesscss','arrays','wordpress','facebook','fbml','table','.htaccess','php','c','.net','c#','java']
const separator = ', '
const result = array_of_strings.reduce((accumulator, currentValue) => accumulator + separator + currentValue);
console.log(result)
Dmytro Huz
  • 1,514
  • 2
  • 14
  • 22