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.
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.
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";
How to Use Variable in Regex in Python
How to Mount Remote Filesystem in Linux
How to Copy Files from Linux to Windows