maahd
maahd

Reputation: 712

Array to more than one string

I have a JavaScript array:

cities = ["LA", "NYC", "Riyadh", "Frankfurt"]

The cities.toString() function will give me

"LA, NYC, Riyadh, Frankfurt"

How do I get

"LA", "NYC", "Riyadh", "Frankfurt"

Upvotes: 2

Views: 63

Answers (3)

stanze
stanze

Reputation: 2480

You can use join function of array to join the array elements using any separator like:

var result = '"' + cities.join('", "') + '"' ;

Check the working demo fiddle

Upvotes: 1

Alexander
Alexander

Reputation: 20224

If you want to change an array into a string, there's array.join. It works well with whatever delimiter you want to use:

var array = ["LA", "NYC", "Riyadh", "Frankfurt"];
var string = '"' + array.join('", "') + '"';
// Result: "LA", "NYC", "Riyadh", "Frankfurt"

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239443

The simplest way I can think of is to use JSON.stringify and drop the first and last characters with slice, like this

var cities = ["LA", "NYC", "Riyadh", "Frankfurt"]
console.log(JSON.stringify(cities).slice(1, -1));
// "LA","NYC","Riyadh","Frankfurt"

If you want it, exactly like you mentioned in your answer, use map function to generate new Strings surrounded by double quotes and finally join them with , like this

console.log(cities.map(function (currentCity) {
    return '"' + currentCity + '"';
}).join(', '));
// "LA", "NYC", "Riyadh", "Frankfurt"

If your actual strings will not have any , in them, then you can chain the split and join calls, like this

console.log(JSON.stringify(cities).slice(1, -1).split(",").join(", "));
// "LA", "NYC", "Riyadh", "Frankfurt"

Upvotes: 3

Related Questions