use variable in regex in javascript

How to Use Variable in Regex in JavaScript

Regular expressions (Regex) make it easy to search and replace substrings and patterns in larger strings. They are supported in almost every programming language. They are available in back end scripting languages such as python, perl as well as front-end languages such as JavaScript. Generally, people use fixed string literals such as numbers & alphabets to define regular expressions. But sometimes you may need to use a variable in regular expression. In this article, we will learn how to use variable in Regex in JavaScript.


How to Use Variable in Regex in JavaScript

Here are the steps to use variable in regex in JavaScript. Let us say you have the following string.

"ABABAB"

Let us say you want to replace all occurrences of ‘B’ with ‘A’ in the above string. Here is how we typically do it using regular expression and replace() function.

"ABABAB".replace(/B/g, "A");

Let us say you want to pass ‘B’ via a variable, and do something as shown below.

var test = 'B';
"ABABAB".replace(/test/g, "A");

The above code will replace all occurrences of ‘test’ with A but not all occurrences of ‘B’ with ‘A’. In other words, ‘test’ is interpreted as a literal string and not a variable. So how do we overcome this problem?

First, we define a variable as done above.

var replace = "test";

Next, we create a regular expression using the above variable, with the help of RegExp() function.

var re = new RegExp(replace,"g");

Finally, we use the regular expression re in replace() function to replace desired string or characters.

"ABABAB".replace(re, "newstring");

This time, replace() function will treat re as regular expression and not literal string.

Please note, if your variable’s value has special regex characters such as \d, you need to escape it using another backslash. For example, if you want to create a regular expression with ‘B’ followed by digits, then here is how you should define it in variable.

var replace = "B\\d";

In this article, we have learnt how to use variable in regex in JavaScript. Basically, you need to first call RegExp() function in your variable, to create a regular expression from it. Then you need to use the resultant regular expression in replace() or wherever you need it.

Also read:

How to Use Variable in Regex in Python
How to Split Array into Chunks in JavaScript
How to Print Number With Commas as Thousands Separators in JavaScript
How to Mount Remote Filesystem in Linux
How to Copy Files from Linux to Windows

Leave a Reply

Your email address will not be published.