Open In App

How to use a Variable in Regular Expression in JavaScript ?

Last Updated : 15 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Regexps can be used in JavaScript to build dynamic patterns that match various strings depending on the value of the variable. In this article, we will see how to utilize the variable with the regular expression. In this article, we will see, how to use a Variable in Regular Expression in JavaScript

Below are the approaches on How to use a Variable in Regular Expression in JavaScript

Syntax:

Using Regular expressions literal and then concatenating

// Initializing an GFG variable
let GFG = "GeeksForGeeks";

// Using Regular expression
const myRegex = `Hello ${GFG}`

Using the Concatenation

The regular expression pattern must be properly formatted and any special characters must be appropriately escaped before employing concatenation. To escape special characters, you can employ string escape sequences, such as for a literal backslash or s for a whitespace character.

Example 1: In this example, Matching a word containing a variable string of letters.

Javascript




let GFG = 'geeks';
let regex = new RegExp('^[a-z]+' + GFG + '[a-z]+$');
 
console.log(regex.test('heygeekshello'));
console.log(regex.test('geekshello'));


Output

true
false

Example 2: In this example, Matching a number containing a phone number.

Javascript




let pinCode = '121';
let regex = new RegExp('^\\(' + pinCode
    + '\\)\\s\\d{3}-\\d{4}$');
 
console.log(regex.test('(121) 123-4567'));
console.log(regex.test('(123) 123-4567'));


Output

true
false

Using the Interpolation (Template Literal)

Using interpolation the variable is merely inserted into the pattern using the template literal’s $ syntax.

Example 1: In this example, Matching a word containing a variable string of letters.

Javascript




let GFG = 'geeks';
let regex = new RegExp(`^[a-z]+${GFG}[a-z]+$`);
 
console.log(regex.test('heygeekshello'));
console.log(regex.test('geekshello'));


Output

true
false

Example 2: In this example, we are matching a number containing a phone number.

Javascript




let pinCode = '121';
let regex = new RegExp(`^\\(${pinCode}\\)\\s\\d{3}-\\d{4}$`);
 
console.log(regex.test('(121) 123-4567'));
console.log(regex.test('(123) 123-4567'));


Output

true
false

Conclusion:

Regular expressions in JavaScript can be made more dynamic and versatile by using variables. Based on the value of a variable, we can build regular expressions with reusable patterns that can match various strings. String concatenation and template literals are the two methods used in JavaScript to use variables in regular expressions.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads