Range of Characters and More Regular Expressions in JavaScript
Welcome to the second part of a five-part series on regular expressions in JavaScript. In the first part we explained why you would want to be familiar with regular expressions and began describing them. In this part we'll pick up where we left off, covering special characters, combining with other characters, character classes, and more.
Range of Characters and More Regular Expressions in JavaScript - Character Classes (Page 3 of 4 )
The Square Brackets
A character class allows a set of possible characters, rather than just a single character, to match at a particular point in a regexp. Character classes are denoted by brackets [...], with the set of characters to be possibly matched inside. Here are some examples:
Let your available string be
He has a cat.
You may know that he has an animal, but it does not matter to you which animal he has. You will be satisfied if he has a cat, bat or a rat. Note that the words, cat, bat and rat each have at but begin with a c or b or r. The regexp to check this is
/[bcr]at/
The following produces a match
/[bcr]at /.test(He has a cat.)
Here, because of the brackets, we interpret the regexp as follows: the test() function should match any word whose first character is a b, c or r, the rest of the characters being "at."
The square brackets denote a class of elements. However, it is any one element in the class that is to be tested, not all of them together.