Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Javascript Array (split string) 1

Status
Not open for further replies.

TommyB44

Technical User
Jun 16, 2005
76
GB
Hi, All

Could anybody tell me how i split a string onto an array.
I know some javascript but not enough to do this, i'll try to
explain....

I have a string that looks like this...

var s="$2111*bob*22*gold$3221*paul*26*silver$5476*sam*45*iron";

note: the amount of '$' characters can be anything from 1 to 15, but the amount of '*' characters is always 3 within the '$' characters.

I'm trying to firstly split the string at the '$' character
as it's the start of a new table row, then split every '*' character into and array so i can name them and use them to write the html, for example if I split the first one i could name it userID...

s[0]=userID;

then use it in html like..

document.write("<span id="+userID+">");

and do the same with the three remaining userName,age,metal)

Thanks for reading, and help or links to point me in the right direction would be great.
 
since you are splitting it twice you're going to have a 2 dimensional array.

Code:
var s="$2111*bob*22*gold$3221*paul*26*silver$5476*sam*45*iron";
var arr = s.split("$").split("*");
alert(arr[1][0]);   //will display 2111

Arrays are indexed starting at 0. However, since your string starts with a $ character the first index of the array will contain nothing. Therefore, the first item in your string appears at arr[1][0].

-kaht

...looks like you don't have a job, so why don't you get out there and feed Tina.
headbang.gif
[rockband]
headbang.gif
 
Since you want them named, I suggest an array of custom objects.
Code:
<script>
var s="$2111*bob*22*gold$3221*paul*26*silver$5476*sam*45*iron";
var users = s.split("$");
for(i=1;i<users.length;i++){
  user=users[i].split("*");
  users[i]={
    userID: user[0],
    userName: user[1],
    age: user[2],
    metal: user[3]
  }
}

for(i=1;i<users.length;i++){
  document.write("<span id="+users[i].[red]userID[/red]+">");
  document.write(users[i].[red]userName[/red]);
  document.write("</span><br>");
}
</script>

Adam
 
Thanks Alot, Adam, Kaht.

very fast response too.
 
kaht, I don't think your code would work since the split method is only valid on a String object, but the first split returns an Array object. A loop would be needed.

Adam
 
Adam is completely right. I get caught up in stringing methods together like that and that one slipped under the radar, heh.

-kaht

...looks like you don't have a job, so why don't you get out there and feed Tina.
headbang.gif
[rockband]
headbang.gif
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top