HomeJavaScript Page 9 - Understanding the JavaScript RegExp Object
Changing Things Around - 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.
You may have noticed from the previous examples that when using a RegExp object, you have to specify the regular expression at the time of constructing the object. So you might be wondering to yourself, what happens if I need to change the pattern at a later time?
Well, the guys at JavaScript HQ have you covered. The compile() method allows a user to update the regular expression used by the RegExp object in its searches. Take a look:
<script language="JavaScript">
// define string var str = "The Matrix";
// define pattern var pattern = "trinity"
// define object var character = new RegExp(pattern);
// look for match if(character.test(str)) { alert("Looking for " + pattern + "...User located in The Matrix"); } else { alert("Looking for " + pattern + "...Sorry, user is not in The Matrix"); }
// change the pattern associated with the RegExp object var pattern = "tri"; character.compile(pattern);
// look for match and display result if(character.test(str)) { alert("Looking for " + pattern + "...User located in The Matrix"); } else { alert("Looking for " + pattern + "...Sorry, user is not in The Matrix"); }
</script>
Notice the use of the compile() method to dynamically update the pattern associated with the RegExp object.