How to Define Patterns in JavaScript with Regular Expressions

In the previous lesson, we introduced the regular expression, a programming tool used to match patterns in a string. It is built into many different programming languages, and JavaScript is one of them.

The previous lesson focused on how to match a pattern using the built-in methods match() and matchAll(), as well as different matching modes that can be activated by providing the right flag. In this lesson, we are going to cover different ways to describe a pattern using the regular expression.

Matching a set of characters

In a regular expression, you can use a square bracket to match a set of characters instead of just one. For example,

javascript
1let regex = /[01234][56789][abc]/g;
2
3let str1 = "18b"; // matched
4let str2 = "98b"; // null, because 9 is outside of [01234]
5let str3 = "18z"; // null, because z is outside of [abc]
6
7console.log(str1.match(regex));
8console.log(str2.match(regex));
9console.log(str3.match(regex));
text
1[ '18b' ]
2null
3null

This regular expression defines the following pattern:

A number between 0 and 4, followed by a number between 5 and 9, followed by a letter between a and c.

As a result, the str1 falls into this rage, but the other two don't.

There is a easier way to define a range of characters by using a hyphen (-).

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉