HomeJavaScript Page 3 - Understanding the JavaScript RegExp Object
Two to Tango - 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.
Now that you know what a regular expression is, let's look at using it in a script. JavaScript's String object exposes a number of methods that support regular expressions. The first of these is the search() method, used to search a string for a match to the supplied regular expression. Take a look at the next example:
<script language="JavaScript">
// define string to be searched var str = "The Matrix";
// define search pattern var pattern = /trinity/;
// search and return result if(str.search(pattern) == -1) { alert("Sorry, Trinity is not in The Matrix."); } else { alert("Trinity located in The Matrix at character " + str.search(pattern)); }
</script>
When you run this script, you should see the following:
Sorry, Trinity is not in The Matrix.
The search() method returns the position of the substring matching the regular expression, or -1 if no match exists. In the example above, it is clear that the pattern "trinity" does not exist in the string "The Matrix," hence the error message.
Now, look what happens when I update the regular expression so that it results in a positive match:
<script language="JavaScript">
// define string to be searched var str = " The Matrix";
// define search pattern var pattern = /tri/;
// search and return result if(str.search(pattern) == -1) { alert("Sorry, Trinity is not in The Matrix."); } else { alert("Trinity located in The Matrix at character " + str.search(pattern)); }
</script>
This time round, the JavaScript interpreter will return a match (and the location where it found the match). Here's the output: