Java Reference
In-Depth Information
the string objeCt
The main functions making use of regular expressions are the String object's split() , replace() ,
search() , and match() methods. You've already seen their syntax, so in this section you concentrate
on their use with regular expressions and at the same time learn more about regular expression
syntax and usage.
the split() method
You've seen that the split() method enables you to split a string into various pieces, with
the split being made at the character or characters specified as a parameter. The result of this
method is an array with each element containing one of the split pieces. For example, the following
string:
var myListString = "apple, banana, peach, orange"
could be split into an array in which each element contains a different fruit, like this:
var myFruitArray = myListString.split(", ");
How about if your string is this instead?
var myListString = "apple, 0.99, banana, 0.50, peach, 0.25, orange, 0.75";
The string could, for example, contain both the names and prices of the fruit. How could you
split the string, but retrieve only the names of the fruit and not the prices? You could do it without
regular expressions, but it would take many lines of code. With regular expressions you can use the
same code and just amend the split() method's parameter.
Splitting the Fruit String
trY it out
Let's create an example that solves the problem just described—it must split your string, but include
only the fruit names, not the prices:
<!DOCTYPE html>
 
<html lang="en">
<head>
<title>Chapter 6, Example 3</title>
</head>
<body>
<script>
var myListString = "apple, 0.99, banana, 0.50, peach, 0.25, orange, 0.75";
var theRegExp = /[^a-z]+/i;
var myFruitArray = myListString.split(theRegExp);
 
document.write(myFruitArray.join("<br />"));
</script>
</body>
</html>
 
Search WWH ::




Custom Search