Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript print array to string with brackets and quotes

Tags:

javascript

var fruits = ["Banana", "Orange", "Apple", "Mango"];

If I had the above array and wanted to output it to the user in the DOM as ["Banana", "Orange", "Apple", "Mango"]

What would be the best way to do this?

I have tried fruits.toString(); which outputs as Banana,Orange,Apple,Mango

like image 690
ngplayground Avatar asked Apr 29 '15 23:04

ngplayground


3 Answers

Use JSON.stringify

JSON.stringify(fruits)
like image 55
yangli-io Avatar answered Oct 06 '22 00:10

yangli-io


If for some reason you don't want to use JSON, you could also use join.:

var fruits = ["Banana", "Orange", "Apple", "Mango"];

var fruitsString = '["' + fruits.join('", "') + '"]';

Note: For mulitdimensional arrays see javascript - Convert array to string while preserving brackets.

like image 21
am2124429 Avatar answered Oct 06 '22 00:10

am2124429


in order to do that you'll need to iterate through the array and build the string from scratch.

so something like this:

var fruits = ["Banana", "Orange", "Apple", "Mango"];

// first make sure that each fruit is between quotes
var fruitsResult = fruits.map(function(fruit) {
    return '"' + fruit + '"';
});

// join the fruits with the comma's in between
var result = fruitsResult.join(', ');

// add the final brackets around it
result = '[' + result + ']'

This is a basic solution that you can either add as a single function somewhere and pass the array to our you can extend the Array prototype with your own method so you can call fruits.toMyStringFunction(). It's up to you how you want to implement this.

Note: that I'm using the Array.prototype.map() method that is supported in modern browsers but will cause some issues with IE8 and lower. This step can also be done using a for loop but this is more elegant.

like image 30
yopefonic Avatar answered Oct 05 '22 23:10

yopefonic