22 Votes

JavaScript: Convert array to string (comma separated)

Question by Guest | 2011-12-30 at 22:58

I have an array in which some numbers are stored. Now, I would like to turn this array into a string to output it. The numbers in the string should be separated by a comma in the string, like this: "1, 2, 3, 4".

Up to now, I have already tried a lot using loops and all of these things, but somehow, I did not get a result. Can someone help me?

ReplyPositiveNegative
6Best Answer8 Votes

JavaScript makes it very easy for you, so that you do not have to handle your own loops or functions. The function that you are looking for is called join ():

var NumberArray = [1,2,3,4];
var NumberString = NumberArray.join(', ');
alert(NumberString);
// output: "1, 2, 3, 4"

The function join() simply expects the string to be written between the elements as parameter. The return value of join() is then the final string.

In the example above, we are using ', ' (a comma and a space) as separator, but we can also use any other character, we would like to use as delimiter.
2011-12-31 at 18:24

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.