JavaScript Page 3 - Understanding the JavaScript RegExp Object |
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:
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:
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
blog comments powered by Disqus |