Metacharacters, Flags and Regular Expressions in JavaScript
Welcome to the fourth part of a five-part series on regular expressions in JavaScript. In this part, you'll learn about metacharacters, combining matching features, and more.
Metacharacters, Flags and Regular Expressions in JavaScript - Regexps Flags Revisited (Page 4 of 5 )
The literal format syntax for developing the regexp object is
re = /pattern/flags
The i Flag
The i flag is used to make the regexp case insensitive. I have said all there is to say about the i flag.
The g Flag
As I said in the second part of the series, the g flag is not used in a straightforward manner. Execute the following script:
<script type="text/javascript">
var availableString = "A dog is an animal. A dog can be kept at home. There are different species of dogs";
var re = /dog/ ;
if (re.test(availableString))
alert('Matched');
else
alert('Not Matched');
alert(re.lastIndex);
if (re.test(availableString))
alert('Matched');
else
alert('Not Matched');
alert(re.lastIndex);
</script>
The available string is,
“A dog is an animal. A dog can be kept at home. There are different species of dogs.”
The regexp is
/dog/
Note that the global flag has not been used in the regexp.
The same test function has been executed twice in sequence. After each test function the lastIndex property was read. For both cases the number 5 was displayed as the lastIndex (the lastIndex in this case may not be displayed in your browser since the g flag was not used).
The first match occurred for the word "dog" in the first sentence. The second match occurred for the same word in the first sentence. This is okay since the regular expression is always tested against the first match in the available string unless the global flag is used.
Now, add the global flag, g, to the regexp as shown below and execute the script:
var re = /dog/g ;
After the first test, the lastindex is displayed as 5. After the second test the lastIndex is displayed as 25. The first one is displayed after the first "dog" was seen. The second one is displayed after the second "dog," in the second sentence, was seen. Position 25 is the position of the space character after the second "dog."
Note that we have called the test function more than once. The question is this: with the g flag, if you call the test function once, will all the possible matches in the available string be searched for? The answer is no. Only the first possible match will be seen, if you call the test function only once.
You have to call the test function more than once, in sequence, if you want all of the possible matches to be seen. The number of times you call the test function should be equal to the number of possible matches. The best way to do this is to call the test function in a loop until it returns false. The test function returns false when the search through the string is complete.