javascript regex with variable code example
Example 1: javascript use variable regex
var replace = "regex";
var re = new RegExp(replace,"g");
"mystring".replace(re, "newstring")
Example 2: pass variable to regrex literal notation javascript
re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
let inputString = "I'm John, or johnny, but I prefer john.";
let replaceThis = "John";
let re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
console.log(inputString.replace(re, "Jack"));
Example 3: add variable inside regex in javascript
var pattern="cd"
var repeats=3
new RegExp(`${pattern}{${repeats}}`, "g")