The String search() method gives you the index where the match occurs in the available string. Specifically, it gives you the index of the position of the first character of the sub string found in the available string. The following example illustrates this:
var availableString = "We have a dog in our compound.";
var re = /dog/;
var theIndex = availableString.search(re);
The first statement in the script declares the variable for the available string. The next statement declares the variable for the RegExp. Note that there is no global flag here. The statement after this obtains the index as a return value of the search method.
Note: If a match does not occur with the search method, the search method returns –1.
Strictly speaking we cannot compare the behavior of the lastindex property and that of the index returned by the search method. However, note that with the String search() method we do not need the global flag just to know the position of the matched sub-string in the available string.
lastIndex and firstIndex
The RegExp has the lastIndex property; there is no equivalent lastIndex property with the String Regular Expression methods. The String regular expression method "search()" returns what you can call the firstIndex. There is no equivalent firstIndex property or returned value for the RexExp methods (test() and exec()).
Some Notes on RegExp lastIndex
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.