How to Create Regular Expression Patterns and Flags in JavaScript
Regular expressions are one of the most powerful tools in a developer's toolkit. They provide a concise, flexible way to search, match, and manipulate text using patterns. Whether you are validating an email address, extracting data from a log file, replacing text in a document, or parsing complex string formats, regular expressions can accomplish in a single line what would otherwise require dozens of lines of procedural code.
JavaScript has built-in support for regular expressions through the RegExp object and dedicated syntax. This guide covers the two ways to create regular expressions, explains every available flag and when to use each one, and introduces the fundamental methods for searching strings with patterns.
Creating RegExp: Literal /pattern/flags and Constructor new RegExp()
JavaScript provides two ways to create a regular expression. Both produce a RegExp object, but they differ in syntax, timing, and use cases.
Literal Syntax: /pattern/flags
The most common way to create a regular expression is with the literal syntax, using forward slashes as delimiters:
const regex = /hello/;
const regexWithFlags = /hello/gi;
The pattern goes between the slashes, and flags (optional) go immediately after the closing slash. No quotes are used.
const digitPattern = /\d+/g; // One or more digits, global search
const emailPattern = /\S+@\S+\.\S+/; // Simple email pattern
const wordBoundary = /\bcat\b/i; // The word "cat", case-insensitive
The literal syntax is evaluated at parse time (when the JavaScript engine reads the source code). This means the pattern is fixed and cannot be changed at runtime.
Constructor Syntax: new RegExp(pattern, flags)
The constructor syntax creates a regular expression from strings:
const regex = new RegExp('hello');
const regexWithFlags = new RegExp('hello', 'gi');
The first argument is the pattern as a string, and the second (optional) argument is the flags as a string.
const digitPattern = new RegExp('\\d+', 'g');
const wordBoundary = new RegExp('\\bcat\\b', 'i');
Notice the double backslashes in the constructor syntax. Because the pattern is a regular JavaScript string, backslashes need to be escaped. The string '\\d' produces the two-character sequence \d, which the RegExp engine then interprets as "any digit." A single backslash '\d' would be interpreted by the JavaScript string parser first, potentially producing an unintended character.
// These are equivalent:
const regex1 = /\d+\.\d+/; // Literal: backslashes are for regex
const regex2 = new RegExp('\\d+\\.\\d+'); // Constructor: double backslashes
// ❌ Common mistake: single backslash in constructor
const broken = new RegExp('\d+');
// '\d' in a string is just 'd' (no special meaning)
// This creates the regex /d+/, not /\d+/
When to Use Each Syntax
Use literal syntax when the pattern is known at development time and will not change:
// Fixed patterns: use literals
const isEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const hasDigit = /\d/;
const isHexColor = /^#[0-9a-f]{6}$/i;
Use the constructor when the pattern needs to be dynamic, built from variables, or determined at runtime:
// Dynamic pattern: must use constructor
function findWord(text, word) {
const regex = new RegExp(`\\b${word}\\b`, 'gi');
return text.match(regex);
}
let ris = findWord('The cat sat on the mat', 'cat');
console.log(ris) // ["cat"]
// Pattern from user input
function highlightSearch(text, searchTerm) {
const escaped = searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(escaped, 'gi');
return text.replace(regex, '<mark>$&</mark>');
}