Regular Expressions
Variables
Coding Tips
Programming
JavaScript

How to use a variable inside a regular expression

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Using a variable inside a regular expression is straightforward once you separate two cases: the variable is literal text that must be escaped, or the variable is intentional regex syntax that you want the engine to interpret. Most bugs come from mixing those two cases together.

In practice, the safe default is to treat runtime input as literal text and escape it before building the pattern. The rest of the expression can still use normal regex syntax around that escaped fragment.

JavaScript: Use RegExp, Not a Regex Literal

A JavaScript regex literal is fixed at parse time, so this does not interpolate a variable:

javascript
const prefix = "item";
// Wrong: the variable name is treated as plain text in source code.
// const re = /^prefix-\d+$/;

When part of the pattern is dynamic, build it with new RegExp(...) instead.

javascript
1function escapeRegex(value) {
2  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3}
4
5const prefix = "item.1";
6const re = new RegExp("^" + escapeRegex(prefix) + "-\\d+$");
7
8console.log(re.test("item.1-42"));
9console.log(re.test("itemX1-42"));

The escapeRegex helper is the important part. Without it, the . in item.1 would mean "any character" instead of a literal dot.

Python: Use re.escape for Literal Input

Python has the same rule, but the standard library already provides the escape helper.

python
1import re
2
3prefix = "item.1"
4pattern = re.compile(r"^" + re.escape(prefix) + r"-\d+$")
5
6print(bool(pattern.match("item.1-42")))
7print(bool(pattern.match("itemX1-42")))

re.escape is usually the right answer when user input, configuration values, or file names need to appear literally inside a larger regex.

Combine Literal Variables with Real Regex Syntax

Most dynamic patterns are a mix of fixed regex syntax and escaped variable content. For example, suppose you want a case-insensitive match for a configurable prefix followed by digits.

python
1import re
2
3prefix = "USER+"
4pattern = re.compile(r"^" + re.escape(prefix) + r"\d+$", re.IGNORECASE)
5
6for value in ["USER+123", "user+999", "USERX123"]:
7    print(value, bool(pattern.match(value)))

Only the variable fragment is escaped. Anchors such as ^ and $, character classes, quantifiers, and flags remain part of the regex you are intentionally writing.

When You Should Not Escape

Sometimes the variable is supposed to be regex syntax. Maybe your program lets advanced users configure a pattern such as foo|bar or \d{4}. In that case, escaping would destroy the meaning.

The right design is to decide this explicitly. Do not write code that sometimes treats input as literal and sometimes as regex syntax by accident.

A common approach is:

  • user search text: escape it
  • developer-authored pattern config: do not escape it
  • mixed cases: store literal parts and regex parts separately

Being explicit here makes the code easier to review and much safer.

Anchors and Boundaries Still Matter

Dynamic construction does not change normal regex behavior. If you want a full-string match, add anchors. If you want a word boundary, add a word boundary. Interpolating a variable into a regex without thinking about match scope is how partial matches slip into production.

javascript
1function escapeRegex(value) {
2  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3}
4
5const word = "cat";
6const wholeWord = new RegExp("\\b" + escapeRegex(word) + "\\b", "g");
7console.log("a cat scat category".match(wholeWord));

This matches the standalone word cat, not the cat inside other words.

Readability Counts

Dynamic regex code becomes hard to maintain when everything is concatenated inline. It is usually worth naming the escaped fragment and the final pattern separately.

That small refactor pays off during debugging because you can print the built pattern and inspect whether the variable was escaped correctly.

Common Pitfalls

The most common JavaScript mistake is trying to place a variable inside a regex literal. Another is forgetting to escape literal input before constructing the pattern. Developers also sometimes escape everything, including the regex syntax they actually wanted to keep, which produces patterns that never match. Finally, many dynamic regex bugs are really anchor bugs: the variable was inserted correctly, but the pattern still matched too much because boundaries were never defined.

Summary

  • Treat runtime input as literal text unless you explicitly want regex syntax.
  • In JavaScript, build dynamic patterns with new RegExp(...).
  • Escape literal fragments with a helper such as escapeRegex or Python re.escape.
  • Keep intentional regex syntax separate from escaped variables.
  • Add anchors or boundaries so the match scope is exactly what you intend.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.