Java Reference
In-Depth Information
Within the script block, fi rst you have your string with fruit names and prices.
var myListString = “apple, 0.99, banana, 0.50, peach, 0.25, orange, 0.75”;
How do you split it in such a way that only the fruit names are included? Your fi rst thought might be
to use the comma as the split() method's parameter, but of course that means you end up with the
prices. What you have to ask is, “What is it that's between the items I want?” Or in other words, what
is between the fruit names that you can use to defi ne your split? The answer is that various characters
are between the names of the fruit, such as a comma, a space, numbers, a full stop, more numbers, and
fi nally another comma. What is it that these things have in common and makes them different from the
fruit names that you want? What they have in common is that none of them are letters from a through z.
If you say “Split the string at the point where there is a group of characters that are not between a and z,”
then you get the result you want. Now you know what you need to create your regular expression.
You know that what you want is not the letters a through z, so you start with this:
[^a-z]
The ^ says “Match any character that does not match those specifi ed inside the square brackets.” In this
case you've specifi ed a range of characters not to be matched — all the characters between a and z. As
specifi ed, this expression will match only one character, whereas you want to split wherever there is a
single group of one or more characters that are not between a and z. To do this you need to add the +
special repetition character, which says “Match one or more of the preceding character or group specifi ed.”
[^a-z]+
The fi nal result is this:
var theRegExp = /[^a-z]+/i
The / and / characters mark the start and end of the regular expression whose RegExp object is stored
as a reference in the variable theRegExp . You add the i on the end to make the match case-insensitive.
Don't panic if creating regular expressions seems like a frustrating and less-than-obvious process. At
fi rst, it takes a lot of trial and error to get it right, but as you get more experienced, you'll fi nd creating
them becomes much easier and will enable you to do things that without regular expressions would be
either very awkward or virtually impossible.
In the next line of script you pass the RegExp object to the split() method, which uses it to decide
where to split the string.
var myFruitArray = myListString.split(theRegExp);
After the split, the variable myFruitArray will contain an Array with each element containing the fruit
name, as shown here:
Array Element Index
0
1
2
3
Element value
apple
banana
peach
orange
You then join the string together again using the Array object's join() methods, which you saw in
Chapter 4.
document.write(myFruitArray.join(“<BR>”))
Search WWH ::




Custom Search