How do you use a variable in a regular expression?
In JavaScript, you typically embed a variable into a regular expression by creating a new RegExp
object rather than using the literal syntax (/.../
). This allows you to dynamically build or modify the pattern at runtime. Below are the most common approaches and best practices.
1. Using the new RegExp()
Constructor
When you have a string containing part (or all) of your intended pattern, you can use it like so:
const userInput = 'cat'; const regex = new RegExp(userInput, 'i'); // Matches "cat" (case-insensitive)
userInput
is a variable (e.g., user-provided text, a dynamic value from your application).new RegExp(userInput, 'i')
creates a case-insensitive regex that will match"cat"
in any case (e.g., "Cat", "cAt").
Complex Patterns
If you want additional tokens or anchors, concatenate them in a string:
const userInput = 'dog'; const pattern = '^' + userInput + '$'; const regex = new RegExp(pattern, 'i'); // Matches "dog" exactly (case-insensitive)
- Here, we add the
^
(start of string) and$
(end of string) anchors arounduserInput
.
Escaping Special Characters
If userInput
might contain regex special characters (like ?
, *
, or .
) and you don’t want them to act as part of the regex syntax, you must escape them:
function escapeRegex(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } const rawInput = 'domain.com?query'; const safeInput = escapeRegex(rawInput); const pattern = '^' + safeInput + '$'; const regex = new RegExp(pattern); // Matches the literal string "domain.com?query"
Tip: replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
ensures that any character that could break your pattern is escaped, letting the regex treat it as plain text.
2. Using Template Literals
For readability, you can also build the pattern with template literals:
const userInput = 'cat'; const regex = new RegExp(`^${userInput}$`, 'i');
- Backticks let you embed variables directly with
${variableName}
. - This approach is purely syntactic sugar—under the hood, it’s still just building a string for
new RegExp()
.
3. Avoid Mixing /.../
Literals and Variables
Don’t do something like:
const userInput = 'cat'; const regex = /userInput/; // This won't work as intended
Using the /.../
literal will interpret userInput
as plain text 'userInput'
. JavaScript regex literals cannot contain dynamic variable references; you must use the RegExp
constructor if you need dynamic content.
Example Use Cases
-
Search or Filter:
If you’re building a search feature, the user’s query might become part of your regex. -
Validation:
When validating user input with a partial pattern that needs to be dynamic (e.g., user-defined keywords). -
Transforming Text:
Replacing or highlighting text that matches a user-chosen pattern.
Bonus: Level Up Your JavaScript and Coding Interview Skills
Mastering regex dynamics is just one element of becoming a strong developer. To excel further, consider these DesignGurus.io courses:
-
Grokking JavaScript Fundamentals
Deepen your understanding of closures, prototypes, async/await, and more—crucial for writing robust and efficient JavaScript code. -
Grokking the Coding Interview: Patterns for Coding Questions
Develop a problem-solving mindset with pattern-based solutions—essential for tackling technical interviews and real-world coding challenges.
For personalized feedback, check out their Mock Interview services:
Also, explore the DesignGurus.io YouTube channel for free tutorials on coding patterns and system design.
Final Thoughts
To use a variable inside a regular expression in JavaScript:
- Build your pattern string.
- Pass it to
new RegExp(pattern, flags)
. - Escape special characters if needed.
This approach offers maximum flexibility for scenarios like user-input searches, dynamic validation, and more complex pattern generation.