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 - Matching a Sub-String with its Sub-Sets (Page 3 of 5 )
Consider the following script:
<script type = "text/javascript">
var availableString = "small and medium and big. Another phrase";
var re = /small.*(and).*(medium).*big/;
var myArray = re.exec(availableString);
alert(myArray);
</script>
The available string is "small and medium and big. Another phrase." The regexp is,
/small.*(and).*(medium).*big/;
A subset is identified by parentheses. There are two subsets in the regexp, which are (and) and (medium). The entire regexp will match the sub-string "small and medium and big" in the available string. The subset "and," that is, the first "and" in the sub-string will then be matched, and then the subset "medium" in the sub-string will also be matched.
So the first element in the result array will be "small and medium and big" as expected. The next result array element will be "and," which is the first element officially matched to be remembered. The third element in the result array will be "medium" which is the second element officially matched to be remembered.
So to match subsets of a sub-string, put each sub-string between parentheses in the regexp.