Use Variable Inside Regex in JavaScript

Learn how to use a variable inside regex in JavaScript with RegExp, template literals, and practical replacement examples.

Published

Updated

Read time 2 min read

Reviewed byDeepak Prasad

Use Variable Inside Regex in JavaScript

Using a variable inside regex in JavaScript is a common need when the pattern changes at runtime. The usual solution is to build the expression with the RegExp constructor and a template literal.

This is useful for dynamic searches, replacements, and validation rules where the pattern is not hardcoded. If you are working on broader text cleanup too, JavaScript replaceAll with regex is the related article.

Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.


Build a regex from a variable

The RegExp constructor lets you insert a variable into the pattern string.

javascript
const inputString = "I am John, or johnny, but I prefer john.";
const name = "John";
const re = new RegExp(`\\b${name}\\b`, "gi");
console.log("regex-variable:", inputString.replace(re, "Jack"));
Output

You should see one line logging regex-variable: I am Jack, or johnny, but I prefer Jack..

Use this when the search text changes at runtime.


Use a variable for direct replacement

You can create the pattern from the variable and reuse it in replace().

javascript
const str = "pattern";
const re = new RegExp(str, "g");
console.log("regex-fixed:", "pattern matching".replace(re, "regex"));
Output

You should see one line logging regex-fixed: regex matching.

This is a simple way to build dynamic search and replace behavior.


Escape user input before building the regex

If the variable can contain special regex characters, escape it before building the pattern.

javascript
const userInput = "a.b";
const safePattern = userInput.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const safeRegex = new RegExp(safePattern, "g");
console.log("regex-safe:", "a.b and aab".replace(safeRegex, "match"));
Output

You should see one line logging regex-safe: match and aab.

That is the safer choice when the input comes from a user or an external source.


Summary

To use a variable inside regex in JavaScript, build the pattern with RegExp() and a template literal, then escape user input before you interpolate it. That approach is the safest way to handle dynamic search and replace logic because it keeps the pattern flexible without letting regex metacharacters break the expression. It is especially useful for text filtering, replacements, and validation rules that change at runtime.


Official documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …