Match from a class of characters
If you want to match against a set of characters, you can place the set inside []
. For example, [abc]
would mean any character a
, b
, or c
:
var pattern = /[abc]/; console.log(pattern.test('a')); //true console.log(pattern.test('d')); //false
You can specify that you want to match anything but the pattern by adding a ^
(caret sign) at the beginning of the pattern:
var pattern = /[^abc]/; console.log(pattern.test('a')); //false console.log(pattern.test('d')); //true
One critical variation of this pattern is a range of values. If we want to match against a sequential range of characters or numbers, we can use the following pattern:
var pattern = /[0-5]/; console.log(pattern.test(3)); //true console.log(pattern.test(12345)); //true console.log(pattern.test(9)); //false console.log(pattern.test(6789)); //false console.log(/[0123456789]/.test("This is year 2015")); //true
Special characters such as $
and period (.
) characters either represent matches to something other...