Wednesday, July 3, 2024
HomeLanguagesJavascriptHow to use a Variable in Regular Expression in JavaScript ?

How to use a Variable in Regular Expression in JavaScript ?

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.

Concatenation and interpolation are the two main methods for including variables in regular expressions. Whereas interpolation requires inserting the variable directly into the regular expression pattern using template literals, concatenation entails combining the variable with a string to generate the regular expression pattern. 

Syntax:

Using Regular expressions literal and then concatenating

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

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

Approach: Concatenation and interpolation are the two basic methods used in JavaScript to use a variable in a regular expression.

  • 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.
  • Interpolation(Template Literal Approach): Using interpolation the variable is merely inserted into the pattern using the template literal’s $ syntax.

Using the Concatenation:

  • Matching a word containing a variable string of letters.

Javascript




let GFG = 'neveropen';
let regex = new RegExp('^[a-z]+' + GFG + '[a-z]+$');
  
console.log(regex.test('heyneveropenhello')); 
console.log(regex.test('neveropenhello'));


Output:

true
false
  • 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):

  • Matching a word containing a variable string of letters:

Javascript




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


Output:

true
false
  • 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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Ted Musemwa
As a software developer I’m interested in the intersection of computational thinking and design thinking when solving human problems. As a professional I am guided by the principles of experiential learning; experience, reflect, conceptualise and experiment.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments