String Objects and Regular Expressions in JavaScript
Welcome to the fifth article in a five-part series on JavaScript regular expressions. In this article, we begin the second and final phase of the series. In this phase we shall deal more with the properties and methods of the regexp object. We shall also deal with some properties and methods of the string object that are related to regular expressions.
String Objects and Regular Expressions in JavaScript - Remembering a Match (Page 2 of 5 )
It is true that when you use the following syntax, the match is remembered in the result array (one element).
var myResultArr = regexp.exec(availableString)
However, the official way to remember a match is to put what you are looking for in parentheses. So if you have the available string,
var availableString = "I have a dog in my house";
and you want to match "dog," your regexp should be
var re = /(dog)/
The next code segment is as before, that is:
var myArray = re.exec(availableString);
alert(myArray);
The result array here is different from the one we have been seeing. The result array we have been seeing has just one element. The one here has two elements.
The content for the array's zero index element is "dog." The content of the array's element at index 1 is still dog. What happened is that the entire regexp was matched by the exec method as usual. This gave the first element of the result array. Then the exec method went on to match what was in the parentheses. This gave the second element of the result array.
The second element of our result array is officially what the match remembered. It is determined from the subset '(dog)' in the regexp. We shall talk more about subset and matching below.
The JavaScript symbol for remembering a match is (x). In our case, x is "dog."
Forgetting a Match
The opposite of the above is to match and forget. The JavaScript symbol for forgetting a match is (?:x). Note the colon between the question mark and x. Consider the following script:
<script type = "text/javascript">
var availableString = "I have a dog in my house";
var re = /(?:dog)/;
var myArray = re.exec(availableString);
alert(myArray);
</script>
The entire content of the regexp, which is "dog," is matched. This matched "dog" from the available string is the zero index element of the result array. There is only one element for the result array here. The subset is (?:dog); effectively, (dog) is matched, but it is not remembered. So there is no second element for the result array.