Introduction
I was using the regex replace all, but found out it had errors replacing certain reserved characters without escaping them first. So I wrote a custom method, it seems to work pretty well. Please, help test with internet explorer and windows. Also, please let me know if I have goofed with string pointer positions. I haven't fully tested it yet, but I hope it is flawless. Thanks!
Please speed test it here.
http://jsperf.com/javascript-replace-all/8[^]
http://jsperf.com/javascript-replace-all/10[^]
JavaScript - Prototype Version
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;
}
if(s.length>0){ r+=o.substring(o.length-s.length, o.length); }
return r;
};
How to use:
'Test to see if this works? (Yes|No)'.replaceAll('(Yes|No)', 'Yes!');
'Test to see if this works? (Yes|No)'.replaceAll('(yes|no)', 'Yes!', true);
JavaScript - Direct Function Version
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;
}
if(s.length>0){ r+=o.substring(o.length-s.length, o.length); }
return r;
}
How to use:
replaceAll('Test to see if this works? (Yes|No)', '(Yes|No)', 'Yes!');
replaceAll('Test to see if this works? (Yes|No)', '(yes|no)', 'Yes!', true);
PHP - Direct Function Version
function replaceAll($_s, $_f, $_r, $_c=false)
{
$o = $_s;
$r = '';
$s = $o;
$b = 0;
$e = -1;
if($_c){ $_f = strtolower($_f); $s = strtolower($o); }
while(($e=strpos($s, $_f))!=false)
{
$r .= substr($o, $b, ($b + $e)) . $_r;
$s = substr($s, ($e + strlen($_f)), strlen($s));
$b += $e + strlen($_f);
}
if(strlen($s)>0){ $r.=substr($o, (strlen($o) - strlen($s)), strlen($o)); }
return $r;
}
How to use:
replaceAll('Test to see if this works? (Yes|No)', '(Yes|No)', 'Yes!');
replaceAll('Test to see if this works? (Yes|No)', '(yes|no)', 'Yes!', true);
Javascript - Prototype REGEX Version
DO NOT USE! HAS ISSUES WITH CHARACTERS!
String.prototype.replaceAll = function()
{
return this.toString().replace(new RegExp(arguments[0], 'g' +
((arguments[2])? 'i': '') ), arguments[1]);
};