Understanding the JavaScript RegExp Object - Changing Things Around (Page 9 of 11 )
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.
Next: Working with Forms >>
More JavaScript Articles
More By Harish Kamath, (c) Melonfire