Metacharacters, Flags and Regular Expressions in JavaScript
(Page 1 of 5 )
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.
Matching Alternatives
We can match different character strings with the alternation metacharacter "|." To match "dog" or "cat," we form the regexp /cat|dog/ . JavaScript will first try to match the first alternative, "cat." If cat doesn't match, JavaScript will then try the next alternative, "dog." If "dog" doesn't match either, then the match fails (the test() method returns false).
Some examples
The following produces a match:
/cat|dog|bird/.test("cats are a group of animals")
Here, "cat" is matched. There is no "dog" or "bird" in the available string.
Note that in the available string, it is the group of letters, "c," "a" and "t" that is matched. It is not "cats" that is matched. There is no "s" after “cat” in the regexp; "cat" is a string among all the characters in the available string that is matched. Also note that it is not a word that is matched, but a sub-string. Note as well that the space in the available string is a character, which could be a member of a string subset. What I have just said applies to all other matching, not only alternatives.
The following produces a match:
/cat|dog|bird/.test("dogs are a group of animals")
Here "dog" is matched. There is no "cat" or "bird" in the available string. The search did not see "cat," so it matched "dog."
The following produces a match:
/cat|dog|bird/.test("birds are a group of animals")
Here "bird" is matched. There is no "cat" or "dog" in the available string. The search did not see "cat" or "dog," so it matched "bird."
Now, in the following expression, "cat" and not "dog" is matched.
/cat|dog|bird/.test("cats and dogs are groups of animals")
This is because "cat" appears first in the available string, before "dog."
Also, in the following expression "cat" and not "dog" is matched.
/dog|cat|bird/.test("cats and dogs are groups of animals")
Despite the fact that "dog" is the first alternative in the regexp, "cat" appears first in the available string, before "dog," hence the match.
Next: Metacharacters >>
More JavaScript Articles
More By Chrysanthus Forcha