How to use a variable in regex pattern in JavaScript?

Find out how to create and use variables in regex (regular expression) patterns in JavaScript.

This tutorial will show you how to create dynamic regex patterns using variables and the RegExp constructor.

That will improve your text search and replace operations with this powerful technique.

Aside from that, this article will guide you to have a clear understanding of how to create and use the JavaScript regex (regular expression) with variable.

What is regex?

A Regular Expression, commonly known as regex for short, is a powerful tool that helps you find specific patterns in strings.

It’s like a fancy search function that allows you to use symbols, collections of patterns, and special characters to create complex search patterns.

You can use regex to find and replace specific parts of a string or to check if an input follows a certain format.

It’s a handy feature used by many programming languages and applications to perform advanced text searches and validations.

JavaScript has built-in features that support regular expressions. You can use the RegExp object along with methods like test()match()replace(), and split() to work with regular expressions in your code.

How to include a variable within a regex (regular expression) by using the RegExp object

To use a variable inside regex (regular expression in JavaScript, you need to use the RegExp constructor.

This ensures that the variable is replaced correctly.

The RegExp constructor has two parameters: the regular expression itself and an optional flags parameter.

If you use a literal regular expression, the variable won’t be substituted.

On the other hand, flags can be used to modify the behavior of the regular expression, such as making it case-sensitive or case-insensitive.

For example:

let str = "pattern";
let re = new RegExp(str, "g");
console.log("This is just a Sample using pattern".replace(re, "regex"));

Output:

This is just a Sample using regex

In case you want the regular expression to directly utilize the value from the “before” variable. Here’s another example:

function myReplace(str, before, after) {


let re = new RegExp("\\b(" + before + ")\\b","g");
return str.replace(re,after);
  
}

console.log(myReplace("This is just a samplecode from Samplecode!", "Samplecode", "Itsourcecode"));

Output:

This is just a samplecode from Itsourcecode!

How to use regex (Regular Expression) with variable pattern in JavaScript?

In JavaScript, you have two ways to use a variable in a regex (regular expression) pattern.

The first method is to create a new RegExp object using the RegExp() constructor and passing the variable as an argument.

The second method is to create the pattern as a string and use the new RegExp() constructor to generate a RegExp object.

Or you can use the replace() method on another string and include the variable as the parameter for replacement.

Here’s the different way to use “regex.”

1. Using a variable in regular expressions with the “RegExp()” Constructor

To use a variable in regex (regular expressions) in JavaScript, you can rely on the RegExp() constructor. Just assign a string to a variable and you’re good to go.

For example:

const str = "Welcome to Sample";
const word = "Sample";
const regex = new RegExp(word);
const newString = str.replace(regex, "Itsourcecode!");
console.log(newString);

In this example, you have to specify the value you want to replace.
Then, use the RegExp() constructor by passing the chosen word as a parameter.

After that, apply the replace() method, using the created variable as the regular expression parameter.

Display the output on the console using the console.log() method and the variable newString, where the replaced words are stored.

By doing this, you can see how the specified word gets replaced using a variable in a regular expression.

Output:

Welcome to Itsourcecode!

2. Using a variable with the “replace()” method in regular expressions

To use a variable in a regular expression with the replace() method, start by assigning a string to a variable.

For example:

const x = "The sample have the best sourcecode projects";
const newString = x.replace("sample", "itsourcecode");
console.log(newString);

After that, use the replace() method with the suitable parameters to replace words within a string.

And display the output on the console by using the console.log() method and passing the variable newString, where the replaced words are stored.

Output:

The itsourcecode has the best sourcecode projects

3. Using template literals

You can also make dynamic regular expressions more easily by using template literals.

For example:

var variable = 'itsourcecode';
var expression = `.*${variable}.*`;
var re = new RegExp(expression, 'g');
console.log(re.test('sample')); 
console.log(re.test('itsourcecode'));

in the example code, we creates a regular expression that matches any string containing the value of variable, which is itsourcecode.

The first console.log statement logs false because the string sample does not contain itsourcecode, while the second console.log statement logs true because the string itsourcecode contains itsourcecode.

Output:

false
true

Frequently Asked Questions(FAQ’s)

How do to create a regex (regular expression using variables) in JavaScript?

If you want to create a regular expression using variables, you can employ the RegExp constructor.

For example, if you have a variable called “sample” that holds your desired pattern, you can create a regular expression by using the following syntax:

var regex = new RegExp(sample);

How to escape characters in a regex pattern?

To escape characters in a regex pattern, you can use a backslash (\) before the character you want to escape. For example, if you want to match a literal dot (.), you would write it as (/./) in the regex pattern.

It is possible to use variables in the replace function as well?

Absolutely! You can use variables in the replace() function. This function allows you to replace matches of a regex pattern with a specific string or the result of a function.

By using variables, you can dynamically generate the replacement string.

Conclusion

In conclusion, this article discusses how to use variables in regular expressions (regex) in JavaScript.

Regex helps find patterns in strings. JavaScript supports regex through the RegExp object and related methods.

By using the RegExp constructor and other techniques, you can create dynamic regex patterns using variables.

This improves text search and replace operations, enhancing the power and flexibility of your JavaScript code.

The article provides examples of using variables with the RegExp constructor, the replace() method, and template literals.

These techniques allow you to create flexible and efficient regex patterns based on the value of variables.

We are hoping that this article provides you with enough information that helps you understand the JavaScript regex (regular expression) with variable.

You can also check out the following article:

Thank you for reading itsourcecoders 😊.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.
Caren Bautista

Technical Writer at PIES IT Solution

Responsible for crafting clear, well-structured, and beginner-friendly content across the platform. Handles the writing, proofreading, and editorial review of tutorials, guides, and documentation to ensure every article is accurate, readable, and easy to follow.

Expertise: Technical Writing · Content Creation · Documentation · Editorial Writing · JavaScript · TypeScript · Python · Python Errors · HTTP Errors · MS Excel  · View all posts by Caren Bautista →

Leave a Comment