some_bloody_fool
some_bloody_fool

Reputation: 4685

How do I use Javascript to perform a string split and access the values of an Array?

I have been trying to perform a split, but so far I have not had success.

Here is what I have so far:

I initialize a simple String:

var str = "matt.williams:STRING:ClassWork|1902122:STRING:AskAFriend";

My next step is then to output the values of the Array:

var m = str.split("|");
var x = new Array();
x=m;

for (z in x)
{
    document.write(z + "<br />");
}

However, it produces this:

0
1

But What I want to output is this:

matt.williams:STRING:ClassWork
1902122:STRING:AskAFriend

Upvotes: 2

Views: 188

Answers (4)

Adam Rackis
Adam Rackis

Reputation: 83356

Your for loop is giving you the indexes of your array, not the actual values. Change it to:

for (z in x)
{
    document.write(x[z] + "<br />");
}

Or just use an old fashioned for loop:

for(var i = 0; i < x.length; i++)
{
    document.write(x[i] + "<br />");
}

Upvotes: 2

natedavisolds
natedavisolds

Reputation: 4295

Both of these answers are correct, I just wanted to add that split() returns an Array so you don't need to add another.

var str = "matt.williams:STRING:ClassWork|1902122:STRING:AskAFriend";
var m = str.split("|");

for (z in m) {
    document.write(m[z] + "<br />");
}

Upvotes: 0

jmulligan
jmulligan

Reputation: 104

You don't need to set so many variables. You can split and iterate on the returned array.

str.split("|").forEach(function(i){ document.write(i+"<br />"); });

Upvotes: 2

regality
regality

Reputation: 6554

Change this line:

document.write(z + "<br />");

to

document.write(x[z] + "<br />");

Upvotes: 5

Related Questions