Hurry! Try our new Interactive Courses for FREE. 🥳   🚀
Written By:
iamabhishek
5 minute read
JavascriptHowToRegexString

How to use a Variable in Regular Expression pattern in JavaScript?

Posted in Programming   LAST UPDATED: SEPTEMBER 16, 2021

To make a regular expression dynamic, we can use a variable to change the regular expression pattern string by changing the value of the variable. But how do we use dynamic (variable) string as a regex pattern in JavaScript?

We can use the JavaScript RegExp Object for creating a regex pattern from a dynamic string.

Here is the solution for you:

var dynamicPart = "XYZ";
// \074 is code for < and \076 is code for >
var regexObj = new RegExp("\074" + dynamicPart + "\076");    // will match <XYZ>
// the line above is same as, var regex = /\074abc\076/;

var input = "<XYZ> Some text </XYZ>";
var output = regexObj.test(input);

console.log(output);


true

In the above code example, we are matching a custom HTML tag, and the above script can be used to match any HTML tag, but just replacing the value for the dynamicPart variable, because that will automatically update the regular expression pattern.

Why do we need Regular Expressions?

In JavaScript, Regular Expressions also known as regex are patterns used to match, replace, compare character combinations in strings.

When we search for some specific data in a text, we can use a regular expression to be used as a search pattern to describe what you are searching for.

A regular expression can be a single character or a more complicated pattern.

We can use regex to perform any type of text search and text replace operations.

There are two different ways of using a regular expression in JavaScript, they are:

  1. Using RegExp object's constructor function

  2. Using Regular Expression Literal

Escaping Characters in Regular Expression Pattern:

We do not have to escape most of the characters, like we can see in the example above, the code works perfectly. But if the dynamic part or the value of the variable which will be added dynamically has a \ (backslash) which has meaning in regular expression pattern, then we should escape this by adding another backslash.

Yes, to escape any special character in regular expression string, we add a backslash in front of it.

For example,

var dynamicPart = "\s*XYZ";
// \074 is code for < and \076 is code for >
var regexObj = new RegExp("\074" + dynamicPart + "\076");    // will match <XYZ>
// the line above is same as, var regex = /\074abc\076/;

var input = "< XYZ> Some text </XYZ>";
var output = regexObj.test(input);

console.log(output);

If you look closely in the code above, we have added a \s* tin the dynamicPart variable, which is to match spaces, newlines, etc. We have also changed <XYZ> in the input variable to < XYZ> (added a space). But the above code will return false as output, because when the RegExp object will get created it will have s* in the pattern rather than \s*, hence we must escape the backslash with another backslash.

Hence the variable in the code above should be,

var dynamicPart = "\\s*XYZ";

So this is an important point to keep in mind. To check the RegExp object that gets created after the variable is added to the regex pattern, you can use the console.log() statement to print the value of the regex in the console.

Using Template Literals:

There is another simpler way of making dynamic regular expressions using template literals.

Here's a quick example:

var variable = 'foo';
var expression = `.*${variable}.*`;
var re = new RegExp(expression, 'g');
re.test('fdjklsffoodjkslfd')   // true
re.test('fdjklsfdjkslfd')   // false

As you can see in the code example above, we have added a variable to a dynamic regex using template literals ${ }.

Conclusion:

So now you can easily make your regular expressions dynamic to handle different scenarios in your code, where you may need to change some part of your regular expression pattern to match. If you face any issues, feel free to comment below and we will be happy to help.

You may also like:


IF YOU LIKE IT, THEN SHARE IT

RELATED POSTS