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)); ...
Get JavaScript: Functional Programming for JavaScript Developers now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.