98

I want to perform a global replace of string 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 mystring. No quotes for the expression.

But if I have a variable to find, how can I do this without quotes?

I've tried something like this:

var stringToFind = "test";

//first try

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

//second try, not much sense at all

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

but they don't work. Any ideas?

1

13 Answers 13

231
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) ;
  }
1
  • You could've made this simpler: alert(mystring.replace(new RegExp("world", "g"), "yay"))
    – ColorCodin
    May 4, 2018 at 16:41
107

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);
8
  • 3
    +1 always good to see people thinking beyond the literal answer to the question.
    – Thomas
    Feb 13, 2009 at 4:40
  • I wonder how this degrades for larger strings in comparison to the RegExp() call?
    – Kato
    Oct 25, 2011 at 22:24
  • 3
    @Kato I was curious too, so I created a jsperf performance test to find out. link: goo.gl/cbZiV Jan 27, 2013 at 17:48
  • 1
    Just check firefox, and Regex is fastest. (I used chrome before) Jan 27, 2013 at 17:59
  • 1
    @starbeamrainbowlabs very interesting results! Good old IE; always unpredictably bad at random, seemingly important things : )
    – Kato
    Jan 27, 2013 at 18:28
45

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.

0
16
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

1
  • 2
    My implementation is slightly stricter str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\,\\\^\$\|\#\s]/g, '\\$&') Apr 16, 2013 at 15:20
13

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);
1
  • 1
    This is the most clean version of this I could find. This should be the accepted answer !
    – schankam
    Oct 11, 2018 at 4:36
4

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

var r = new RegExp(stringToFind, 'g');
mystring.replace(r, 'some replacement text');
3

Try:

var stringToFind = "test";
mystring = mystring.replace(new RegExp(stringToFind, "g"), mystring);
1
  • 1
    I suppose the last' mystring' in the replace is not what you meant?
    – KooiInc
    Feb 12, 2009 at 19:28
3

You can do using 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|gi}

where

  • g is global case-sensitive replacement
  • gi is blobal case-insensitive replacement

You can check this JSBIN link

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

1

If you want variables interpolated, you need to use the 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

Dynamic global replace

I came to this thread looking for a slightly more complex solution which isn't answered here. I've now found the answer so I'm going to post it in case anyone else finds it useful.

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

For example, to capitalise the first letter of all words (e.g. "cat sat mat" into "Cat Sat Mat") with a global find replace. Here's how to do that.

function capitaliseWords(aString) {
    // Global match for lowercase letters following a word boundary
    var letters = aString.match(/\b[a-z]/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"
0

While not possible when the question was posted, you can now use String.replaceAll:

mystring = mystring.replaceAll(stringToFind, stringToReplace);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll

-1

WIth modern day linters, they prefer you to regEx literal, so rather than new RegExp it would just be `//

With an example:

'test'.replace(/ /gi, '_')

with the test you are looking to replace inside the regex or the /searchableText/ and then replace text in the second parameter. In my case I wanted to replace all spaces with underscores.

-23

Can you use prototype.js? If so you could use String.gsub, like

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"

It will also take regular expressions. To me this is one of the more elegant ways to solve it. prototypejs gsub documentation

3
  • 18
    There's a much simpler solution which actually pretty efficient: myStr.split('a').join('g'). Doesn't require prototype.js either.
    – cloudfeet
    Oct 24, 2013 at 11:28
  • 3
    This is not a helpful answer as there are easy standards-compliant ways to accomplish the same thing.
    – rmcclellan
    Aug 8, 2014 at 15:51
  • @cloudfeet: Your's is indeed a very simple solution but just wondering which one will be more efficient - Using a RegExp object (solution by Paolo Bergantino below) or your solution which creates an array on the fly and then joins the array elements ? May 6, 2016 at 0:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.