return 0
return 0

Reputation: 4366

javascript: How to convert a array of string into a pure string that concatenate the items separated by comma?

I have an javascript array of string that looks like:

A = ['a', 'b', 'c'];

I want to convert it to (all string):

strA = '"a","b","c"'

How do I achieve this?

Upvotes: 1

Views: 417

Answers (4)

Tushar
Tushar

Reputation: 87203

You can use join with "," as glue.

var strA = '"' + A.join('","') + '"';

join will only add the glue between the array elements. So, you've to add the quotes to start and end of it.

Upvotes: 4

jmancherje
jmancherje

Reputation: 6633

You could try just concatenating the values in a simple for loop something like this:

var array = ["1", "a", 'b'];
var str = '';
for (var i = 0; i<array.length; i++){
  str += '"' + array[i] + '",';
}
str = str.substring(0, str.length - 1);

or if you're feeling crazy you could do :

   str = JSON.stringify(array)
   str = str.substring(1, str.length -1);

Upvotes: 0

goodfriend0
goodfriend0

Reputation: 303

Do you mean something like this? This works in chrome.

function transformArray(ar) {
  var s = ar.map(function (i) { 
    return "\"" + i + "\","; })
  .reduce(function(acc, i) { 
    return acc + i; 
  });
  return s.substring(0, s.length-1);
}

transformArray(["a", "b", "c"]);

Upvotes: 0

Antony
Antony

Reputation: 171

Try this

A = ['a', 'b', 'c'];
A.toString();
alert(A);

Upvotes: 1

Related Questions