Regular expressions, popularly known as "regex" or "regexp," are strings that describe a search pattern. You can use regular expressions to check if a string contains a specific pattern, extract information from a string, and replace parts of a string with new text.

Learn the basic syntax of regular expressions and how to use them in JavaScript.

The Basic Syntax of Regular Expressions

There are two ways you can create a regular expression in JavaScript: using a regular expression literal and using the RegExp constructor.

A regular expression literal consists of a pattern enclosed between forward slashes, followed by an optional flag.

For example:

        // Without flag
const regexExpression_1 = /pattern/

// With flag
const regexExpression_2 = /pattern/flag

A flag is an optional parameter that you can add to a regular expression to modify its behavior. For example:

        const regexFlag = /the/g;

The g flag indicates that the expression should match all occurrences, not just the first.

You can also create a regular expression using the RegExp constructor. For example:

        const regexExpression = new RegExp("Pattern", "g");

The RegExp constructor takes two parameters: a pattern—a string or a regular expression literal—and a flag(s).

There are two fairly common flags you’ll use with regular expression in JavaScript:

  • g: The global flag makes the regular expression match all the pattern’s occurrences in the given string instead of a single occurrence.
  • i: The case-insensitive flag makes the regular expression disregard the case of the pattern and match uppercase and lowercase characters in the given string.

You can use flags together in a single expression in any order. For example:

        const regexExpression = new RegExp("Pattern", "gi");

This expression will match all occurrences of “Pattern”, irrespective of the case.

Regular Expression Metacharacters

In regular expressions, certain characters, known as metacharacters, have special meanings. You can use them to match specific types of characters or patterns.

Here are some of the most commonly used metacharacters and their meanings:

  • The Wildcard Character (.): This character matches any single character except for a new line. It’s a useful tool for matching patterns with unknown characters.
  • The Kleene Star (*): This character matches zero or more occurrences of the preceding character or group. It allows the preceding character or group to appear any number of times in the string, including zero.
  • The Optional Character (?): This character matches zero or one occurrence of a preceding character or group.
  • Start of Line Anchor (^): This character only matches the beginning of a line or string.
  • End of Line Anchor ($): This character matches the end of a line or string.
  • Character Set/Class ([]): A character set matches any character from a set of characters in a string. You define them using square brackets [] and you can specify a set of fixed characters, special characters, or certain groups of characters.
  • Alternation Character (|): This character matches the preceding or the following character or group. It works similarly to the OR JavaScript operator.
  • Grouping Character (()): The grouping character allows you to group characters or sub-expressions, apply operators to them as a unit, and control the order of operations.

Testing a String Against a Regular Expression in JavaScript

In JavaScript, you can test a string against a regular expression using several methods.

This section assumes you have a basic understanding of regular expressions and patterns. If you are uncomfortable with regular expressions, check out a beginner’s guide to regular expressions first.

The test Method

The .test() method returns a boolean indicating whether the regular expression matches the string or not. This method takes a string to perform the search on as an argument. It is particularly useful for simple checks.

For example:

        let regex = /.com$/;
let str = "example.com";
console.log(regex.test(str)); // true

This regular expression matches a string that ends with ".com".

The exec Method

The .exec() method returns an array containing the matched text and any captured groups or null if it doesn’t find a match. This method takes a string to perform the search on as an argument. It is useful for more complex regular expressions.

For example:

        let regex = /^\\(?([0-9]{3})\\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
let str = "123-456-7890";
let result = regex.exec(str);

if (result !== null) {
  console.log(`${result[0]} is a valid phone number`);
} else {
  console.log("Invalid phone number");
}

The regular expression above matches a string that starts with an optional "(", three digits, and an optional ")". It then looks for an optional "-", ".", or space, followed by three digits. It finally looks for an optional "-", ".", or space followed by four digits at the end of the string.

This regular expression matches phone numbers in the format of “(xxx) xxx-xxxx”, “xxx-xxx-xxxx”, “xxx.xxx.xxxx”, or “xxx xxx xxxx”.

If it finds a match, .exec() returns an array containing the matched text and any captured groups (defined by parentheses). It will include each group as an additional element in the array it returns. This allows you to access specific parts of the matched text, which can help you extract information from a string.

The replace Method

The .replace() method searches for a match between a regular expression and a string and replaces the matched text with a specified replacement text. This is a method of string objects, and it takes a regular expression and a replacement string as arguments.

For example:

        let string = "The quick brown fox jumps over the lazy dog.";
let expression = /The/gi;
let newString = string.replace(expression, "a");
console.log(newString); // "a quick brown fox jumps over a lazy dog."

This example calls the replace() method on the string variable, passing the regular expression, expression. The regular expression will match all occurrences of “The” in the string, irrespective of the case. The call to the replace method instructs it to replace each occurrence with the string “a”.

Performance Considerations While Using Regular Expressions

Although regular expressions help match and manipulate strings, they can also be costly in terms of performance. Making patterns as specific as possible and keeping them simple is vital to keep them performant.