Understanding the JavaScript RegExp Object - Two to Tango (Page 3 of 11 )
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:
Trinity located in The Matrix at character 7