1

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?

6
  • 1
    do you mean 'a, b , c' -> strA = A.join(', ') - Array.join() Commented Oct 16, 2015 at 6:04
  • No. I meant literally \"a\",\"b\",\"c\", I am just looking for a simple solution Commented Oct 16, 2015 at 6:05
  • 2
    Or '"' + A.join('", "') + '"'; Commented Oct 16, 2015 at 6:06
  • @tushar very beautiful answer Commented Oct 16, 2015 at 6:08
  • @Tushar not required... you can post that... was suppose to add that.. then saw you have already posted it as a comment Commented Oct 16, 2015 at 6:09

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Minor adjustment: var strA = '"' + A.join('","') + '"';
@davejagoda Removed space from glue
1

Try this

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

1 Comment

No quotes around a, b and c.
0

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"]);

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.