How to use a Variable in a Regular Expression in JavaScript
Table of Contents
Regular expressions are useful because they are a powerful way to match patterns in strings.
However, sometimes the thing you want to match for is coming from a variable. For example, you might want to match for a string that is stored in a variable.
In this post, we will learn how to use a variable in a regular expression in JavaScript.
Using a variable in a regular expression
Let's say that you are trying to replace the word "dog" with the word "cat" in a string. You could do this with the following code:
JAVASCRIPTconst string = "The dog is happy.";
const newString = string.replace("dog", "cat");
console.log(newString);
BASHThe cat is happy.
Now, this works but it isn't using a regular expression. Let's accomplish the same task as above but using a regular expression.
JAVASCRIPTconst string = "The dog is happy.";
const newString = string.replace(/dog/, "cat");
console.log(newString);
BASHThe cat is happy.
Now, let's say instead of replacing the word "dog" with the word "cat", you want to replace the word that is stored in a variable.
We can't just use the variable in the regular expression because it will be interpreted as a string. Instead, we need to use the RegExp
constructor.
JAVASCRIPTconst string = "The dog is happy.";
const word = "dog";
const regex = new RegExp(word);
const newString = string.replace(regex, "cat");
console.log(newString);
BASHThe cat is happy.
By using the RegExp
constructor, we can use a variable in a regular expression.
Conclusion
In this post, we learned how to use a variable in a regular expression in JavaScript.
Simply use the RegExp
constructor to create a regular expression from a variable.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- Getting Started with Deno
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- Getting Started with Handlebars.js
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- How To Create a Modal Popup Box with CSS and JavaScript