Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you replace a certain part of a string JavaScript?

replace() is an inbuilt method in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged. Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.

How do you change the value of a global variable inside of a function using JavaScript?

To change the value of a global variable inside of a function with JavaScript, we can assign the global variable to a new value. a = 10; const myFunction = () => { a = 20; }; myFunction(); to set the global variable a to 20 in the myFunction function.

How do you find and replace a character in a string in JavaScript?

Answer: Use the JavaScript replace() method You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.


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.


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


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