Defining a Regular Expression

Learn about the two ways to define a regular expression in JavaScript.

Now that we’ve gotten the formal bits out of the way, let’s get to the nitty-gritty, shall we?

In this chapter, we’re going to be defining everything you need in order to understand the specific regular expression flavor that JavaScript uses. Remember: there are several similar ones out there, but we’re going with a subset of PCRE.

The two ways to define a RegExp

Let’s start at the beginning. For you to define a RegExp, JavaScript offers two different ways, each one with its pros and cons:

  1. You can use literal notation, just as we saw before with Perl, where you define a regular expression by starting and ending it with a / character.

  2. Or you can use a string passed as parameter into the constructor of the RegExp object. In this case, the / characters aren’t needed.

The following code snippet shows exactly what the two ways look like:

Get hands-on with 1200+ tech skills courses.