O'Reilly logo

Mastering JavaScript by Ved Antani

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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)); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required