How to put variable in regular expression match with JavaScript?

You can put a variable in a regular expression match by using the RegExp constructor, which accepts variables as patterns. This is essential when you need dynamic pattern matching in JavaScript.

Syntax

// Using RegExp constructor with variable
let pattern = new RegExp(variableName, flags);
string.match(pattern);

// Or directly with match()
string.match(variableName); // for simple string matching

Example: Using Variable in Regular Expression

let sentence = 'My Name is John';
console.log("The actual value:");
console.log(sentence);

let matchWord = 'John';
console.log("The matching value:");
console.log(matchWord);

// Using RegExp constructor with variable
let matchRegularExpression = new RegExp(matchWord, 'g');
let result = sentence.match(matchRegularExpression);
console.log("Match result:");
console.log(result);
The actual value:
My Name is John
The matching value:
John
Match result:
[ 'John' ]

Using Different Flags

let text = 'JavaScript is great. I love JavaScript!';
let searchTerm = 'javascript';

// Case-insensitive search using 'i' flag
let caseInsensitive = new RegExp(searchTerm, 'gi');
console.log("Case-insensitive match:");
console.log(text.match(caseInsensitive));

// Global search for exact case
let exactCase = new RegExp('JavaScript', 'g');
console.log("Exact case matches:");
console.log(text.match(exactCase));
Case-insensitive match:
[ 'JavaScript', 'JavaScript' ]
Exact case matches:
[ 'JavaScript', 'JavaScript' ]

Special Characters in Variables

let textWithSpecialChars = 'Price: $25.99 and $15.50';
let dollarPattern = '\$\d+\.\d+';

// Using variable with escaped special characters
let priceRegex = new RegExp(dollarPattern, 'g');
let prices = textWithSpecialChars.match(priceRegex);
console.log("Found prices:");
console.log(prices);
Found prices:
[ '$25.99', '$15.50' ]

Comparison of Methods

Method Use Case Supports Flags
string.match(variable) Simple string matching No
new RegExp(variable, flags) Dynamic regex with flags Yes
/literal/flags Static patterns only Yes

Conclusion

Use new RegExp(variable, flags) when you need dynamic pattern matching with variables. This approach provides flexibility for runtime pattern creation and supports all regex flags.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements