Java Reference
In-Depth Information
The String Object — split(), replace(),
search(), and match() Methods
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 you'll 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 us to split a string into various pieces, with the split being
made at the character or characters specifi ed 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.
Try It Out Splitting the Fruit String
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 PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<body>
<script type=”text/JavaScript”>
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>
Save the fi le as ch9_examp4.htm 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.
Search WWH ::




Custom Search