How do you use a variable in a JavaScript regular expression?

Here’s a detailed breakdown with multiple examples demonstrating how to dynamically inject variables into JavaScript regular expressions, handle edge cases, and apply them in real-world scenarios:

1. Basic Variable Injection

Dynamically create a regex pattern from a variable:

const username = "john_doe";
const regex = new RegExp(`^${username}$`, "i"); // Case-insensitive match
console.log(regex.test("John_Doe")); // true ✅

2. Case-Insensitive Search with Flags

Use variables for both pattern and flags:

const searchTerm = "hello";
const flags = "gi"; // Global + Case-insensitive
const regex = new RegExp(searchTerm, flags);
const matches = "Hello world! HELLO universe!".match(regex);
console.log(matches); // ["Hello", "HELLO"] ✅

3. Escaping Special Characters

Safely escape metacharacters in user input:

function escapeRegex(text) {
  return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // Escape all special chars
}

const userInput = "file[2023].txt";
const safePattern = escapeRegex(userInput); // "file\[2023\]\.txt"
const regex = new RegExp(safePattern);
console.log(regex.test("file[2023].txt")); // true ✅

4. Combining Variables with Static Patterns

Build complex patterns using template literals:

const domain = "example.com";
const path = "/api";
const regex = new RegExp(`^https?://${domain}${path}`, "i");
console.log(regex.test("https://example.com/api")); // true ✅

5. Dynamic Flags Based on Conditions

Toggle regex flags programmatically:

const isCaseSensitive = false;
const flags = isCaseSensitive ? "" : "i"; // Use 'i' flag if case-insensitive
const regex = new RegExp("Hello World", flags);
console.log(regex.test("hello world")); // true ✅ (if isCaseSensitive=false)

6. Replace Substrings Dynamically

Use a variable in a replacement regex:

const oldValue = "{{username}}";
const newValue = "Alice";
const text = "Welcome, {{username}}!";
const regex = new RegExp(escapeRegex(oldValue), "g"); // Escape special chars
const updatedText = text.replace(regex, newValue);
console.log(updatedText); // "Welcome, Alice!" ✅

7. Validate User Input Against a Dynamic Pattern

Check if input matches a dynamic rule:

const allowedExtensions = ["txt", "pdf", "docx"];
const extensionPattern = allowedExtensions.join("|"); // "txt|pdf|docx"
const regex = new RegExp(`\\.(${extensionPattern})$`, "i");
console.log(regex.test("report.PDF")); // true ✅

8. Advanced: Lookaheads and Groups

Use variables inside regex constructs:

const minLength = 8;
const regex = new RegExp(`^(?=.*\\d)(?=.*[a-z]).{${minLength},}$`); // Password validation
console.log(regex.test("pass1234")); // true ✅ (8+ chars, has digit and lowercase)

Key Takeaways

  • Syntax: Always use new RegExp(variable, "flags") instead of /.../ literals.
  • Escape Variables: Sanitize input with special characters using escapeRegex.
  • Template Literals: Combine variables and static patterns seamlessly with backticks.
  • Security: Avoid using unescaped user input directly in regex to prevent ReDoS attacks.

By mastering these patterns, you can create flexible and secure regular expressions tailored to dynamic data!

Leave a Reply

Your email address will not be published. Required fields are marked *