1// CREATE A REGEXP object
2var replace = "regex";
3var re = new RegExp(replace,"g");
4//then use
5"mystring".replace(re, "newstring")
1// If you want to get ALL occurrences (g), be case insensitive (i), and use boundaries so that it isn't a word within another word (\\b):
2
3re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
4
5// example:
6
7let inputString = "I'm John, or johnny, but I prefer john.";
8let replaceThis = "John";
9let re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
10console.log(inputString.replace(re, "Jack")); // I'm Jack, or johnny, but I prefer Jack.
11