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
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.
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.
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.
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.
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
Use array.join(", ");
and it should work
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# :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With