Java Reference
In-Depth Information
Save the file as ch6 _ example3.html and load it in your browser. You should see the four fruits from
your string written out to the page, with each fruit on a separate line.
Within the script block, first 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 first 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 define 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
finally 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 specified inside the square brackets.” In this
case you've specified a range of characters not to be matched—all the characters between a and z. As
specified, 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 specified”:
[^a-z]+
The final 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
first, it takes a lot of trial and error to get it right, but as you get more experienced, you'll find 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
Search WWH ::




Custom Search