JavaScript print array to string with brackets and quotes

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.


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.


Use JSON.stringify

JSON.stringify(fruits)

Tags:

Javascript