Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join an array by a comma and a space

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
like image 316
Myles Gray Avatar asked Feb 22 '11 15:02

Myles Gray


People also ask

How do you join an array with spaces?

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

How do you get a comma-separated value from an array?

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 put a space after a comma in a string?

Use the replaceAll() method to add a space after each comma in a string, e.g. str. replaceAll(',', ', ') . The replaceAll() method will return a new string, where all occurrences of a comma are replaced with a comma and a space.

How do you create an array with comma-separated strings?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.


3 Answers

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

like image 106
Nick Craver Avatar answered Oct 21 '22 02:10

Nick Craver


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

like image 23
adarshr Avatar answered Oct 21 '22 03:10

adarshr


 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# :)

like image 2
John xyz Avatar answered Oct 21 '22 02:10

John xyz