HomeJavaScript Page 4 - Understanding the JavaScript RegExp Object
Game, Set, Match - JavaScript
Need to match and replace patterns on a Web page? You don't need Perl or PHP - JavaScript can do the job just as well. In this article, find out how, with an introduction to the JavaScript RegExp object and its methods. After reading this tutorial, I'm pretty sure you're going to look at JavaScript in a different light. The language ins't the one most commonly associated with image swaps and browser detection, but it serves as a powerful tool to help you execute pattern-matching tasks in the client quickly and efficiently.
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);
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);
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.