Understanding the JavaScript RegExp Object - Game, Set, Match (Page 4 of 11 )
The String object also comes with a match() method, which can be considered a close cousin of the search() method above. What's the difference? Well, you've already seen that the search() method returns the position where a match was found. The match() method does things a little differently; it applies a regex pattern to a string and returns the values matched in an array.
Confused? Take a look at the next example
<script language="JavaScript">
// define string
var str = "Mississippi";
// define search pattern
var pattern = /is./;
// check for matches
// place result in array
var result =
str.match(pattern);
// display matches
for(i = 0; i < result.length; i++)
{
alert("Match #" + (i+1) + ": " + result[i]);
}
</script>
View this example in a browser, and you'll get an alert message displaying the first matching result, as shown below:
Match #1: iss
In the example above, I have defined a regular expression "is." This will match the string "is", followed by any other character (the "." operator at the end of the pattern matches anything and everything in a string). If you look at the string to be searched, you'll see that there are two occurrences of this pattern. However, the code above only returns 1.
Why?
The answer is simple - I've "forgotten" to add the "g" (for "global") modifier to the pattern. As a result, searching stops after the first match. Consider the next example, which revises the previous code listing to add this operator:
<script language="JavaScript">
// define string
var str = "Mississippi";
// define search pattern
// add global modifier
var pattern
= /is./g;
// check for matches
// place result in array
var result =
str.match(pattern);
// display matches
for(i = 0; i < result.length; i++)
{
alert("Match #" + (i+1) + ": " + result[i]);
}
</script>
And now, when you try out this example, you should see two alert boxes, indicating that two matches to the specified pattern were found in the string. The additional "g" modifier ensures that all occurrences of a pattern in a string are matched, and stored in the return array. I'll show you a few other useful modifiers as we proceed through this tutorial.
Next: Search and Destroy >>
More JavaScript Articles
More By Harish Kamath, (c) Melonfire