Understanding the JavaScript RegExp Object - Objects in the Rear-View Mirror (Page 7 of 11 )
So far, all the examples in this article have piggybacked on the String object to demonstrate the power of the regex implementation in JavaScript. But JavaScript also comes with a core JavaScript object, the RegExp object, whose sole raison d'etre is to match patterns in strings and variables.
This RegExp object comes with three useful methods. Take a look:
test() - test a string for a match to a pattern
exec() - returns an array of the matches found in the string, and also permits advanced regex manipulation
compile() - alter the regular expression associated with a RegExp object
Let's look at a simple example:
<script language="JavaScript">
// define str
var str = "The Matrix";
// define RegExp object
var character = new RegExp("tri");
// search for pattern in string
if(character.test(str)) {
alert("User
located in The Matrix.");
} else {
alert("Sorry, user is not in The
Matrix.");
}
</script>
This is similar to one of the very first examples in this tutorial. However, as you can see, I've adopted a completely different approach here.
The primary difference here lies in my creation of a RegExp object for my regular expression search. This is accomplished with the "new" keyword, followed by a call to the object constructor. By definition, this constructor takes two parameters: the pattern to be searched for, and modifiers if any (I've conveniently skipped these in the example above).
Once the RegExp object has been created, the next step is to use it. Here, I've used the test() method to look for a match to the pattern. By default, this method accepts a string variable as a parameter and compares it against the pattern passed to the RegExp object constructor. If it finds a match, it returns true; if it does not, it returns false. Obviously, this is a more logical implementation than the search() feature of the String object.
Next: One Mississippi, Two Mississippi... >>
More JavaScript Articles
More By Harish Kamath, (c) Melonfire