Forum Moderators: open

Message Too Old, No Replies

building strings

simple string building query

         

ironik

3:11 am on Mar 14, 2005 (gmt 0)

10+ Year Member



Hi all,

I'm not too javascript savy, but well versed in server side programming with PHP. Can anyone tell me how I can build a string in a loop. I've done a bit of a search and tried endless variations myself, but I'm falling flat because I don't know much about the JS syntax.

Roughly, I have a loop that iterates through the elements in an array and builds a comma seperated string to populate a cookie. I've got the cookie stuff, and rebuilding the array when afterwards, I just can't create the thing properly:

var myString = "";
for (i = 0; i <= myArray.length; i++)
{
myString = myString + myArray[i] + ",";
}
myString = myString.substring(0, -1);

Because I can't get past the building part, I'm not sure if the substring call will work either.

I'd welcome any help! :) Thanks in advance

Bernard Marx

8:51 am on Mar 14, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Converting the array to a string will produce just what you want. You can do this by calling the toString method explicitly, but it will also happen implicitly when the array is 'added' to a string.

myArray = [1,2,3]
cookieString = myArray.toString();
//or//
cookieString = myArray+'';

If you want another delimiter than a comma, use the join method:

myString = myArray.join('¦');

BTW, you needed < array.length (not <=),
and substring(0,-1) won't cut it. Need
myString.substring(0,myString.length-1)

ironik

9:40 pm on Mar 14, 2005 (gmt 0)

10+ Year Member



Thanks!

Javascript syntax is something I'm still trying to get my head around :)

Cheers,
Ironik