In Javascript, how can I perform a global replace on string with a variable inside '/' and '/g'?

var mystring = "hello world test world";
var find = "world";
var regex = new RegExp(find, "g");
alert(mystring.replace(regex, "yay")); // alerts "hello yay test yay"

In case you need this into a function

  replaceGlobally(original, searchTxt, replaceTxt) {
    const regex = new RegExp(searchTxt, 'g');
    return original.replace(regex, replaceTxt) ;
  }

For regex, new RegExp(stringtofind, 'g');. BUT. If ‘find’ contains characters that are special in regex, they will have their regexy meaning. So if you tried to replace the '.' in 'abc.def' with 'x', you'd get 'xxxxxxx' — whoops.

If all you want is a simple string replacement, there is no need for regular expressions! Here is the plain string replace idiom:

mystring= mystring.split(stringtofind).join(replacementstring);

Regular expressions are much slower then string search. So, creating regex with escaped search string is not an optimal way. Even looping though the string would be faster, but I suggest using built-in pre-compiled methods.

Here is a fast and clean way of doing fast global string replace:

sMyString.split(sSearch).join(sReplace);

And that's it.