JavaScript - How to Use a Variable in Regular Expression? Last Updated : 04 Dec, 2024 Summarize Comments Improve Suggest changes Share Like Article Like Report To dynamically create a regular expression (RegExp) in JavaScript using variables, you can use the RegExp constructor. Here are the various ways to use a variable in Regular Expression.1. Using the RegExp Constructor with a VariableIn JavaScript, regular expressions can be created dynamically using the RegExp constructor. This method allows you to pass a string as the pattern and optionally specify flags for the regular expression. JavaScript let search = "hello"; let regex = new RegExp(search, "i"); // Case-insensitive search let s = "Hello, how are you?"; let res = regex.test(s); console.log(res); Outputtrue search: A variable that contains the word you want to search for in the string.new RegExp(search, "i"): This dynamically creates a regular expression based on the search variable. The "i" flag makes the search case-insensitive.test(str): The test() method checks if the regular expression matches the string str.2. Using Variables to Create More Complex PatternsYou can use variables to dynamically create more complex regular expressions as well, such as matching multiple words or patterns. JavaScript let w1 = "apple"; let w2 = "banana"; let regex = new RegExp(w1 + "|" + w2, "i"); let s = "I like both apple and banana."; let res = regex.test(s); console.log(res); Outputtrue w1 + "|" + w2: This creates a pattern that matches either "apple" or "banana". The | symbol is used as an OR operator in regular expressions.new RegExp(w1 + "|" + w2, "i"): Dynamically creates the regular expression.test(): Checks if the pattern matches the string.3. Using Variables for Flags in Regular ExpressionsYou can also dynamically set the flags of a regular expression. This is useful if you want to apply different search options based on certain conditions. JavaScript let pattern = "hello"; let flag = "i"; let regex = new RegExp(pattern, flag); let s = "Hello world!"; let res = regex.test(s); console.log(res); Outputtrue flag = "i": The flag is stored in a variable, which you can change dynamically.new RegExp(pattern, flag): The regular expression is constructed using both the pattern and the flag variable.test(): The method checks if the regular expression matches the string.4. Special Case: Escaping Special Characters in VariablesWhen using a variable in a regular expression, you might need to escape special characters (like ., *, +, etc.) that could interfere with the regular expression syntax. JavaScript let pattern = "hello.world"; let escapedPat = pattern.replace(/[.*+?^=!:${}()|\[\]\/\\]/g, "\\$&"); let regex = new RegExp(escapedPat); let s = "hello.world"; let res = regex.test(s); console.log(res); Outputtrue replace(/[.*+?^=!:${}()|\[\]\/\\]/g, "\\$&"): This line escapes any special characters in the pattern. Special characters in regular expressions need to be escaped to match them literally.new RegExp(escapedPat): After escaping special characters, the escapedPat is used to create a valid regular expression.Use Cases for Using Variables in Regular ExpressionsDynamic Searching: When you need to match a pattern that changes based on user input or some other dynamic data (like matching a search term).Form Validation: Dynamically generate regular expressions based on form input values to validate things like email, phone numbers, or passwords.Text Processing: When processing text files or strings dynamically, you can use variables to build the search pattern based on the data. Comment More infoAdvertise with us Next Article JavaScript - How to Access Matched Groups in Regular Expression? N nikhilgarg527 Follow Improve Article Tags : JavaScript Web Technologies JavaScript-RegExp JavaScript-Questions Similar Reads JavaScript - How Useful is Learning Regular Expressions? Regular expressions (RegExp) are an important skill for JavaScript developers that helps in text manipulation, validation, and extraction. Whether youâre working on form validations, file handling, or log parsing, mastering regular expressions can simplify your code and improve productivity. Why Lea 3 min read How to use regular expression in class path in TestNG.xml? TestNG provides a regular expression in class path features for the testng.xml file. It is useful when you want to run lots of test classes from a package conforming to a particular pattern without listing each class in TestNG.Approach to Using Regular Expressions in Class-Path in testng.xmlTestNG a 3 min read JavaScript - How to Access Matched Groups in Regular Expression? Here are the different methods to access matched groups in JavaScript regular Expression(RegExp).1. Using exec() MethodThe exec() method returns an array with the entire match and captured groups, which you can access by their index in the result array.JavaScriptlet s = "The price is $50"; let regex 3 min read Convert user input string into regular expression using JavaScript In this article, we will convert the user input string into a regular expression using JavaScript.To convert user input into a regular expression in JavaScript, you can use the RegExp constructor. The RegExp constructor takes a string as its argument and converts it into a regular expression object 2 min read JavaScript - How to Create Regular Expression Only Accept Special Formula? To ensure that a string matches a specific formula or pattern, you can use a regular expression (RegExp) in JavaScript. Here are the various ways to create a regular expression that only accepts regular formulas.1: Alphanumeric Code FormulaLet's create a regular expression that matches a formula lik 3 min read JavaScript RegExp (Regular Expression) A regular expression is a special sequence of characters that defines a search pattern, typically used for pattern matching within text. It's often used for tasks such as validating email addresses, phone numbers, or checking if a string contains certain patterns (like dates, specific words, etc.).I 4 min read Like