Course contentsShow
← JavaScript
Lesson 1665 of 2,72336. Regular ExpressionsFree lesson

Creating Regex Patterns: Literals vs Constructor

Two ways to create regex in JavaScript: /pattern/flags syntax and new RegExp() constructor.

Creating Regex Patterns: Literals vs Constructor

You'll learn the two ways to create regular expressions in JavaScript and when to use each.

Just like you can create strings with quotes ("hello") or the String constructor, regular expressions have two creation syntaxes. Understanding both gives you flexibility for different scenarios.

Regex Literal Syntax

The most common way to create a regex is with forward slashes:

const pattern = /hello/;
const caseInsensitive = /hello/i;

The syntax is /pattern/flags. This is concise, readable, and is compiled when your code is parsed (like a string literal). It's the go-to choice when your pattern is known at write-time.

RegExp Constructor Syntax

The alternative is using the RegExp constructor:

const pattern = new RegExp('hello');
const caseInsensitive = new RegExp('hello', 'i');

Here, the pattern is a string (first argument) and flags are a separate string (second argument, optional). This is essential when your pattern needs to be built dynamically at runtime.

When to Use Each

Use literal syntax (/pattern/) when:

  • The pattern is fixed and known when you write the code
  • You want cleaner, more readable code

Use the constructor when:

  • The pattern comes from user input or variables
  • You need to build patterns programmatically
// Literal: pattern known ahead of time
const zipCode = /\d{5}/;

// Constructor: pattern built from a variable
const userWord = 'cat';
const dynamicPattern = new RegExp(userWord); // matches "cat"

Key Takeaway: Use /pattern/ literals for static patterns and new RegExp() when you need to construct patterns dynamically from strings or variables at runtime.