HomeJavaScript Page 8 - Understanding the JavaScript RegExp Object
One Mississippi, Two Mississippi... - 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 next method I'll show you is the exec() method. The behavior of this method is similar to that of the String object's match() method. Take a look:
<script language="JavaScript">
// define string var place = "Mississippi";
// define pattern var obj = /is./;
// search for match // place result in array result = obj.exec(place);
// display result if(result != null) { alert("Found " + result[0] + " at " + result.index); } </script>
The exec() method returns a match to the supplied regular expression, if one exists, as an array; you can access the first element of the array to retrieve the matching substring, and the location of that substring with the index() method.
The main difference between the match() and exec() methods lies in the parameters passed. The former requires a pattern as argument, while the latter requires the string variable to be tested.
However, that's not all. The exec() method has the ability to continue searching within the string for the same pattern without requiring you to use the "g" modifier. Let me tweak the above example to demonstrate this feature:
<script language="JavaScript">
// define string var place = "Mississippi";
// define pattern var obj = /is./;
// search for all matches in string // display result while((result = obj.exec(place)) != null) { alert("Found " + result[0] + " at " + result.index); }
</script>
So what do we have here? For starters, I have used a "while" loop to call the exec() method repeatedly, until it reaches the end of the string (at which point the object will return null and the loop will terminate). This is possible because every time you call exec(), the RegExp object continue to search from where it left off in the previous iteration.
At least that's the theory - the code above doesn't work as advertised in either Internet Explorer or Netscape Navigator, so you should be careful when using it. Consider the above a purely theoretical example, then... at least until the browser makers fix the bug.
Another interesting point to note in the example above is my definition of the RegExp object. Unlike the previous example, you will notice that I have not used the constructor or the "new" keyword to create the object; instead, I've simply assigned the pattern to a variable. Think of this as a shortcut technique for creating a new RegExp object.