Java Reference
In-Depth Information
The match() Method
The match() method is very similar to the search() method, except that instead of returning the posi-
tion at which a match was found, it returns an array. Each element of the array contains the text of a
match made.
For example, if you had the string
var myString = “The years were 1999, 2000 and 2001”;
and wanted to extract the years from this string, you could do so using the match() method. To match
each year, you are looking for four digits in between word boundaries. This requirement translates to
the following regular expression:
var myRegExp = /\b\d{4}\b/g;
You want to match all the years so the g has been added to the end for a global search.
To do the match and store the results, you use the match() method and store the Array object it returns
in a variable.
var resultsArray = myString.match(myRegExp);
To prove it has worked, let's use some code to output each item in the array. You've added an if statement
to double-check that the results array actually contains an array. If no matches were made, the results
array will contain null — doing if (resultsArray) will return true if the variable has a value and
not null.
if (resultsArray)
{
var indexCounter;
for (indexCounter = 0; indexCounter < resultsArray.length; indexCounter++)
{
alert(resultsArray[indexCounter]);
}
}
This would result in three alert boxes containing the numbers 1999, 2000, and 2001.
Try It Out Splitting HTML
In the next example, you want to take a string of HTML and split it into its component parts. For
example, you want the HTML <P>Hello</P> to become an array, with the elements having the follow-
ing contents:
<P>
Hello
</P>
<!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”>
Search WWH ::




Custom Search