JavaScript replace all occurrences of string (v14)

Revision 14 of this benchmark created by bla on


Setup

var i = 0,
        occurrences = 1000,
        string_with_things_to_replace = "We want to replace all instances of 'geoff' in this string with 'REPLACED'. ";
    
    var precompiledRegex = /'/g;

Test runner

Ready to run.

Testing in
TestOps/sec
string.replace(/global regex/g)
string_with_things_to_replace.replace(/'/g, '\'\'');
ready
for loop
for (i=0; i<occurrences; i++) {
    string_with_things_to_replace.replace('\'', 'REPLACED');
}
ready
precompiled
string_with_things_to_replace.replace(precompiledRegex, '\'\'');
ready
prototype-custom
String.prototype.replaceAll = function(_f, _r, _c){ 
  var o = this.toString();
  var r = '';
  var s = o;
  var b = 0;
  var e = -1;
  if(_c){ _f = _f.toLowerCase(); s = o.toLowerCase(); }

  while((e=s.indexOf(_f)) > -1)
  {
    r += o.substring(b, b+e) + _r;
    s = s.substring(e+_f.length, s.length);
    b += e+_f.length;
  }

  // Add Leftover
  if(s.length>0){ r+=o.substring(o.length-s.length, o.length); }

  // Return New String
  return r;
};

string_with_things_to_replace = string_with_things_to_replace.replaceAll('geoff', 'REPLACED');
ready
prototype-regex
/* DO NOT USE - Regex has issues replacing reserved characters unless they are escaped. Found out the hard way! */
String.prototype.replaceAll = function()
{ 
  return this.toString().replace(new RegExp(arguments[0], 'g' +
 ((arguments[2])? 'i': '') ), arguments[1]); 
};

string_with_things_to_replace = string_with_things_to_replace.replaceAll('geoff', 'REPLACED');
ready
function - custom
function replaceAll(_s, _f, _r, _c){ 

  var o = _s.toString();
  var r = '';
  var s = o;
  var b = 0;
  var e = -1;
  if(_c){ _f = _f.toLowerCase(); s = o.toLowerCase(); }

  while((e=s.indexOf(_f)) > -1)
  {
    r += o.substring(b, b+e) + _r;
    s = s.substring(e+_f.length, s.length);
    b += e+_f.length;
  }

  // Add Leftover
  if(s.length>0){ r+=o.substring(o.length-s.length, o.length); }

  // Return New String
  return r;
}

string_with_things_to_replace = replaceAll(string_with_things_to_replace, 'geoff', 'REPLACED');
ready
function - custom case insensitive
function replaceAll(_s, _f, _r, _c){ 

  var o = _s.toString();
  var r = '';
  var s = o;
  var b = 0;
  var e = -1;
  if(_c){ _f = _f.toLowerCase(); s = o.toLowerCase(); }

  while((e=s.indexOf(_f)) > -1)
  {
    r += o.substring(b, b+e) + _r;
    s = s.substring(e+_f.length, s.length);
    b += e+_f.length;
  }

  // Add Leftover
  if(s.length>0){ r+=o.substring(o.length-s.length, o.length); }

  // Return New String
  return r;
}

string_with_things_to_replace = replaceAll(string_with_things_to_replace, 'GEOFF', 'REPLACED', true);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.