In Javascript, how can I do a global replacement in a string with a variable inside '/' and '/ g'?

I want to do a global string replacement using String.replace in Javascript.

In the documentation, I read that I can do this with / g, i.e., for example,

var mystring = mystring.replace(/test/g, mystring); 

and this will replace all occurrences inside the mystring. No quotation marks for expression.

But if I have a variable that can be found, how can I do this without quotes?

I tried something like this:

 var stringToFind = "test"; 

// try first

 mystring = mystring.replace('/' + stringToFind + '/g', mystring); 

// second attempt, not much sense

 mystring = mystring.replace(/stringToFind/g, mystring); 

but they do not work. Any ideas?

+57
javascript string regex
Feb 12 '09 at 16:49
source share
11 answers

Can you use prototype.js? If so, you can use String.gsub, for example

 var myStr = "a day in a life of a thing"; var replace = "a"; var resultString = myStr.gsub(replace, "g"); // resultString will be "g day in g life of g thing" 

He will also accept regular expressions. For me, this is one of the most elegant ways to solve it. prototypejs gsub documentation

-10
Feb 12 '09 at 18:35
source share
 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" 

If you need it in a function

  replaceGlobally(original, searchTxt, replaceTxt) { const regex = new RegExp(searchTxt, 'g'); return original.replace(regex, replaceTxt) ; } 
+169
Feb 12 '09 at 16:53
source share

For the regular expression new RegExp(stringtofind, 'g'); . BUT. If 'find contains characters that are special in the regular expression, they will be regexy. Therefore, if you try to replace "." in 'abc.def' with 'x', you will get "xxxxxxx" screams.

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

 mystring= mystring.split(stringtofind).join(replacementstring); 
+64
Feb 12 '09 at 17:01
source share

Regular expressions are much slower than string searches. Thus, creating a regular expression with an escaped search string is not the best way. Even a loop, although the string will be faster, but I suggest using built-in pre-compiled methods.

Here is a quick and clean way to quickly replace a global string:

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

What is it.

+33
Jan 15
source share
 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); 

post silmiar

+14
Feb 13 '09 at 4:35
source share

This is a regular expression, not a string. Use the constructor for the RegExp object to dynamically create a regular expression.

 var r = new RegExp(stringToFind, 'g'); mystring.replace(r, 'some replacement text'); 
+3
Feb 12 '09 at 16:56
source share

Try:

 var stringToFind = "test"; mystring = mystring.replace(new RegExp(stringToFind, "g"), mystring); 
+2
Feb 12 '09 at 16:55
source share

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

 myString.replace(new RegExp(strFind, 'g'), strReplace); 
+2
Aug 28 '18 at 21:24
source share

If you want variables to be interpolated, you need to use a RegExp object

https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Regular_Expressions

Example:

 var str = "This is my name"; var replace = "i"; var re = new RegExp(replace, 'g') str = str.replace(re, 'p'); alert(str); 
+1
Feb 12 '09 at 16:57
source share

Dynamic global replacement

I came to this topic, looking for a more complex solution, which I did not answer here. Now I have found the answer, so I will post it in case anyone finds it useful.

I wanted to do a dynamic global replacement where replacement strings are based on the original matches.

For example, to smooth out the first letter of all words (for example, "cat sat mat" in "Mat Sat Mat") with the replacement of the global find. Here's how to do it.

 function capitaliseWords(aString) { // Global match for lowercase letters following a word boundary var letters = aString.match(/\b[az]/g), i, letterMatch; // Loop over all matched letters for( i = 0; i < letters.length; i++ ) { // Replace the matched letters with upper case versions letterMatch = new RegExp('\\b'+letters[i]); // EDIT - slight fix aString = aString.replace(letterMatch, letters[i].toUpperCase()); } // Return our newly capitalised string return aString; } alert( capitaliseWords("cat sat mat") ); // Alerts "Cat Sat Mat" 
+1
Jun 14 2018-11-11T00:
source share

You can use the following method

see this function:

 function SetValue() { var txt1='This is a blacK table with BLack pen with bLack lady'; alert(txt1); var txt2= txt1.replace(/black/gi,'green'); alert(txt2); } 

Syntax:

/ SEARCH_STRING / {g |} g

Where

  • g is a global case-sensitive replacement.
  • gi is a case-insensitive blasphemous replacement.

You can check this jsbin link

http://jsbin.com/nohuroboxa/edit?html,js,output

0
Dec 02 '15 at
source share



All Articles