When you have a list of things separated by a delimiter, you generally use
split.
Say you have a list of
names separated
by
commas split takes that list and puts each
of the names into
an
array. For example:
var my_friends = "trixie,moxie,sven,guido,hermes";
var friend_array = my_friends.split(",");
for (var loop=0; loop < friend_array.length; loop++)
{
document.writeln(friend_array[loop] + " is my friend.<br>");
}
This breaks
the
string my_friends into an array of five
elements.
(Happily,
JavaScript creates the array for you automatically, so
you
don't
have to use new Array() to create
it
yourself).
We can use split
to
make the earlier domain grabber easier
to
code:
var the_url = prompt("What's the URL?","");
var first_split = the_url.split("//");
var without_resource = first_split[1];
var second_split = without_resource.split("/");
var domain = second_split[0];
This is much
more
attractive, and easier to understand, right? Here's the
breakdown:
- var the_url = prompt("What's
the
URL?","");
- As before, this requests a URL (let's go
with
"http://www.aleeanne.org.uk/javascript/index.html"
again).
- var
first_split = the_url.split("//");
- This
splits the string into
two pieces: first_split[0] is
"http:"
and
first_split[1]
is
"www.aleeanne.org.uk/javascript/index.html."
- var
without_resource
= first_split[1];
- This just grabs the second
element in the
array, so now
without_resource
is
"www.aleeanne.org.uk/javascript/index.html."
- var
second_split =
without_resource.split("/");
- This
breaks
without_resource into three pieces: www.aleeanne.org.uk,
javascript,
and index.html. See how useful split
is?
- var
domain = second_split[0];
- Now all we have
to do is grab the first
element of the second_split array.
And
voilà! We're
done.
That might seem to be a lot of work
at first, but
you'll get used to
it pretty fast. I personally love
split
it's a special
coding treat.
Now that you've
learned all the fancy
string handling routines
for
cookies, take a breather
you've just digested quite a mouthful of
information. Go for a little
stroll. Have a snack. OK? Then it's time to
learn one last thing before
sallying forth into cookie
country:
associative arrays.
next page»