Question

Using Variables in JavaScript Regular Expressions

Question

How can I use a variable as the pattern in a JavaScript regular expression when replacing all occurrences in a string?

For example, this replaces every B with A:

"ABABAB".replace(/B/g, "A");

I want a reusable method where replaceThis is a variable rather than the literal text replaceThis:

String.prototype.replaceAll = function (replaceThis, withThis) {
  this.replace(/replaceThis/g, withThis);
};

How can the variable be used as the regular expression pattern instead?

Short Answer

You will learn why /pattern/g cannot directly interpolate a JavaScript variable, how to create a dynamic pattern with RegExp, and why escaping is essential when a variable represents ordinary text rather than regex syntax. You will also see simpler modern alternatives for replacing all literal text.

Concept

A regular expression literal is written between slashes, such as /B/g. JavaScript reads this pattern directly from your source code. Therefore, /replaceThis/g means “match the exact letters replaceThis”; it does not look up a variable with that name.

When a pattern must be assembled at runtime, use the RegExp constructor:

const replaceThis = "B";
const pattern = new RegExp(replaceThis, "g");

console.log("ABABAB".replace(pattern, "A")); // "AAAAAA"

This matters because many programs receive search text dynamically: a search box, a configurable separator, imported data, or a user-selected keyword.

However, regular expressions have special characters. If replaceThis is intended to be plain text, values such as . or + must be escaped before constructing the regex. Otherwise, JavaScript interprets them as regex operators instead of literal characters.

Mental Model

Think of /B/g as a preprinted form: the text B is permanently printed on it when the program is written.

new RegExp(replaceThis, "g") is like filling in a blank form at runtime. The value currently stored in replaceThis becomes the pattern.

If the value is ordinary text, escaping it is like putting quotation marks around it: it tells the regex engine, “Treat these characters literally, not as instructions.”

Take Quiz

Syntax and Examples

Use new RegExp(pattern, flags) when the pattern comes from a variable.

const find = "B";
const replacement = "A";

const regex = new RegExp(find, "g");
const result = "ABABAB".replace(regex, replacement);

console.log(result); // "AAAAAA"
  • find supplies the pattern.
  • "g" is the global flag, which replaces every match rather than only the first one.
  • replace() returns a new string. It does not modify the original string.

Safely matching literal variable text

If the variable contains text rather than intentional regex syntax, escape regex metacharacters first:

function escapeRegExp(text) {
  return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

function replaceAllLiteral(text, find, replacement) {
  const pattern = new RegExp(escapeRegExp(find), "g");
  return text.replace(pattern, replacement);
}

console.log(replaceAllLiteral("v1.2 v1.2", "v1.2", "v2.0"));
// "v2.0 v2.0"

The escape function adds a backslash before characters that have special meaning in regex patterns. For example, without escaping, . matches any single character, not a literal period.

Modern literal-text alternative

For literal text, modern JavaScript already provides String.prototype.replaceAll():

const result = "ABABAB".replaceAll("B", "A");
console.log(result); // "AAAAAA"

This is usually clearer and safer when you do not need regex features.

Step by Step Execution

Consider this example:

const find = "B";
const text = "ABABAB";
const pattern = new RegExp(find, "g");
const result = text.replace(pattern, "A");

console.log(result);
  1. find stores the string "B".
  2. text stores "ABABAB".
  3. new RegExp(find, "g") reads the current value of find and creates the equivalent of /B/g.
  4. text.replace(pattern, "A") finds all B matches because of the g flag.
  5. Each B is replaced by A.
  6. result becomes "AAAAAA".
  7. text is still "ABABAB", because strings are immutable and replace() returns a new string.

Real World Use Cases

  • Search-and-replace tools: Replace a word entered into an editor or admin dashboard.
  • Data cleanup: Normalize separators, such as changing all ; characters to , in imported text.
  • Template processing: Replace placeholders such as {{name}} with a supplied value.
  • Log redaction: Replace repeated occurrences of a known token before storing or displaying logs.
  • Configurable parsing: Build a regex from an application setting when the setting intentionally contains regex syntax.

Use a dynamic regex only when regex behavior is needed. For straightforward literal replacement, prefer replaceAll() or split().join() in older environments.

Take Quiz

Real Codebase Usage

Developers commonly separate two cases:

  1. Literal input: Text from a user, configuration, or database should normally be treated as literal text and escaped before creating a regex.
  2. Trusted regex input: A developer-defined pattern may intentionally include syntax such as \\d+ or \\s+; in that case, do not escape it.

A practical utility for literal replacement looks like this:

function escapeRegExp(text) {
  return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

function replaceEveryLiteral(text, search, replacement) {
  if (search === "") {
    return text;
  }

  return text.replace(
    new RegExp(escapeRegExp(search), "g"),
    replacement
  );
}

The guard clause for an empty search string avoids surprising behavior and makes the utility's policy explicit.

Also note that adding methods to built-in prototypes, such as String.prototype, is generally avoided in application code and shared libraries. It can conflict with native methods and other code. Prefer a standalone helper function.

Common Mistakes

Expecting a regex literal to read a variable

const find = "B";
"ABABAB".replace(/find/g, "A"); // Looks for the letters "find"

Use new RegExp(find, "g") instead.

Forgetting the global flag

"ABABAB".replace(new RegExp("B"), "A");
// "AAABAB" — only the first B is replaced

Add the g flag:

"ABABAB".replace(new RegExp("B", "g"), "A");

Not returning the replacement result

function replaceEvery(text, find, replacement) {
  text.replace(new RegExp(find, "g"), replacement);
}

replace() does not mutate text. Return its result:

function replaceEvery(text, find, replacement) {
  return text.replace(new RegExp(find, "g"), replacement);
}

Treating arbitrary text as regex without escaping

const find = ".";
"a.b".replace(new RegExp(find, "g"), "!");
// "!!!" because . matches every character

Escape find when it should represent a literal period.

Using the replacement string without considering $ sequences

In replace(), replacement text interprets sequences such as $& (the matched text) and $1 (a captured group). If replacement text comes from an untrusted or arbitrary source and must be inserted exactly, use a replacement function:

text.replace(pattern, () => replacement);

Comparisons

ApproachBest forExampleImportant detail
Regex literalA fixed pattern written in code/B/gCannot insert a variable directly.
RegExp constructorA pattern built at runtimenew RegExp(find, "g")Escape find if it is literal text.
replaceAll()Replacing every literal substringtext.replaceAll(find, value)Simple choice when regex features are unnecessary.
replace() with a stringReplacing the first literal occurrencetext.replace(find, value)Only the first match is replaced.
split().join()Legacy-compatible literal replacementtext.split(find).join(value)Avoids regex syntax, but is less expressive.

A dynamic regex is useful when you need flags, character classes, boundaries, or other pattern matching. For plain text, replaceAll() communicates intent more clearly.

Take Quiz

Cheat Sheet

// Fixed regex pattern
"ABAB".replace(/B/g, "A");

// Dynamic regex pattern
const pattern = new RegExp(variable, "g");
text.replace(pattern, replacement);

// Escape text before using it as a literal regex pattern
function escapeRegExp(text) {
  return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

const pattern = new RegExp(escapeRegExp(searchText), "g");

// Best for modern literal replacement
text.replaceAll(searchText, replacementText);

// Insert replacement text exactly, including $ characters
text.replace(pattern, () => replacementText);
  • /name/g matches the literal letters name; it does not use a variable named name.
  • The g flag means “all matches.”
  • replace() returns a new string; it does not change the original string.
  • Escape dynamic input unless it is deliberately written as a regex pattern.

FAQ

Can I put ${variable} inside /.../g?

No. Regex literals do not support template interpolation. Use new RegExp(variable, "g").

Why does /replaceThis/g not use my replaceThis variable?

Everything between / delimiters is the regex pattern itself. JavaScript treats replaceThis as literal pattern text.

How do I replace every occurrence of a variable in JavaScript?

For literal text, use text.replaceAll(find, replacement). For a dynamic regex, use text.replace(new RegExp(pattern, "g"), replacement).

Should I use RegExp or replaceAll()?

Use replaceAll() for ordinary literal text. Use RegExp when you need regex matching behavior, such as matching digits, whitespace, or word boundaries.

Why should I escape a variable before creating a regex?

Characters such as ., *, ?, and + have special regex meanings. Escaping makes them match themselves.

Does replace() change the original string?

No. JavaScript strings are immutable. Store or return the value produced by replace().

Is it safe to add my own String.prototype.replaceAll method?

Usually no. Modern JavaScript already has a native replaceAll method, and changing built-in prototypes can create conflicts. Use a named helper function instead.

Take Quiz

Mini Project

Description

Build a small text-cleaning helper that replaces every literal occurrence of a user-provided search term. It demonstrates dynamic regular expressions, safe escaping, global replacement, and returning the new string.

Goal

Create a function that replaces all literal matches, including search terms containing regex characters such as . or +.

Requirements

  • Create an escapeRegExp function for literal search text.
  • Create a replaceEveryLiteral function that accepts text, search text, and replacement text.
  • Replace every occurrence, not only the first occurrence.
  • Return the transformed string without changing the original string.
  • Treat regex metacharacters in the search text as ordinary characters.
Take Quiz

Keep learning

Related questions

View more