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 - The lastIndex Property of the Regexp Object (Page 3 of 5 )
The regexp object can be created in two ways. Either like this:
re = /pattern/flags
or like this:
re = new RegExp("pattern"[, "flags"])
The regexp object, re, has properties. One of the properties is called the lastIndex property.
Consider the following script:
<script type="text/javascript">
re = /boy/;
if (re.test("The boy is good"))
alert('Matched');
else
alert('Not Matched');
alert(re.lastIndex);
</script>
If you execute the above code, the first alert box will show “Matched.” The second one from “alert(re.lastIndex)” will show 7.
The available string is "The boy is good." The sub-string "boy" in the available string is matched. The JavaScript index for string (available string) is zero-based. The lastIndex is the index at which to start the next match. The lastIndex is also zero-based. So the space character after the word "boy" in the available string above is at position number 7. That is why the second alert box shows 7.
The lastIndex property works with the global flag, which I will explain next.
Description of the lastIndex Property
lastIndex is a property of an individual regular expression object.
This property is set only if the regular expression used the "g" flag to indicate a global search. The following rules apply:
If lastIndex is greater than the length of the string, regexp.test and regexp.exec fail, and lastIndex is set to 0.
If lastIndex is equal to the length of the string and if the regular expression matches the empty string, then the regular expression matches input starting at lastIndex.
If lastIndex is equal to the length of the string and if the regular expression does not match the empty string, then the regular expression mismatches input, and lastIndex is reset to 0.
Otherwise, lastIndex is set to the next position following the most recent match.