What’s Inside a Regular Expression?

Take a look at the components that compose a regular expression in JavaScript.

There is a lot of information to cover here, and it can be somewhat intimidating for someone who’s just starting out, so we’ll try to break it down a bit.

Different components in a regular expression

Look at the following image. It shows the main parts of a RegExp.

The main things to note here are:

  • Start and end characters:

    As we’ve already mentioned, literal notation uses them to signal the limits of the regular expression.

  • Flag

    After the ending / of your regular expression, you can add a number of flags, which will affect the behavior of the RegExp engine parsing your expression. In this particular one, the g means the match is done globally on the entire string. Otherwise, once the first match is found, the process stops. We’ll cover all the available flags down below.

  • Capturing groups

    This is a very useful feature from RegExps that allows you to literally capture a portion of the match so you can either replace it with something else or simply extract it for yourself.

  • Non-capturing groups

    These allow you to match a section of the string being analyzed. However, you don’t have access to that portion individually. We’ll explain why they are useful later on.

  • Character classes

    These are your bread and butter, and you’ll be using them left and right since, with them, you’re defining the patterns to match inside each group (i.e., writing a-z means any character from a to z, writing 0-9 means any number between those two, and so on).

There are other parts from the example that we left out because marking out every single special character would be excessive.