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

Solution 1:

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) ;
  }

Solution 2:

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);

Solution 3:

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.

Solution 4:

String.prototype.replaceAll = function (replaceThis, withThis) {
   var re = new RegExp(RegExp.quote(replaceThis),"g"); 
   return this.replace(re, withThis);
};


RegExp.quote = function(str) {
     return str.replace(/([.?*+^$[\]\\(){}-])/g, "\\$1");
};

var aa = "qwerr.erer".replaceAll(".","A");
alert(aa);

silmiar post

Solution 5:

You can use the following solution to perform a global replace on a string with a variable inside '/' and '/g':

myString.replace(new RegExp(strFind, 'g'), strReplace);