JavaScript String Regular Expressions - The String Search Method
(Page 4 of 5 )
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:
<html>
<head>
</head>
<body>
<script type="text/javascript">
var availableString = "We have a dog in our compound.";
var re = /dog/;
var theIndex = availableString.search(re);
alert(theIndex);
</script>
</body>
</html>
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.
In the previous case, it was the RegExp object "re" that acquired the lastIndex value. Here the search method takes the RegExp object "re" as its argument. The last statement in the code displays the index. Index counting in a JavaScript string is zero-based. So the index displayed for the code above should be 10, which is the position of the letter "d" of "dog."
Note: If a match does not occur with the search method, the search method returns –1.
Comparison
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
It might interest you to know what the specification says about the RegExp lastIndex property. This is what the specification, JavaScript 1.5 says:
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.
Next: Extracting Matches >>
More JavaScript Articles
More By Chrysanthus Forcha