http://jszen.blogspot.com/2005/12/safari-and-stringreplace-method.html
update : 2005-12-29
1 2 // replace callback support for safari. 3 (function(){ 4 var default_replace = String.prototype.replace; 5 String.prototype.replace = function(search,replace){ 6 // replace is not function 7 if(typeof replace != "function"){ 8 return default_replace.apply(this,arguments) 9 } 10 var str = "" + this; 11 var callback = replace; 12 // search string is not RegExp 13 if(!(search instanceof RegExp)){ 14 var idx = str.indexOf(search); 15 return ( 16 idx == -1 ? str : 17 default_replace.apply(str,[search,callback(search, idx, str)]) 18 ) 19 } 20 var reg = search; 21 var result = []; 22 var lastidx = reg.lastIndex; 23 var re; 24 while((re = reg.exec(str)) != null){ 25 var idx = re.index; 26 var args = re.concat(idx, str); 27 result.push( 28 str.slice(lastidx,idx), 29 callback.apply(null,args).toString() 30 ); 31 if(!reg.global){ 32 lastidx += RegExp.lastMatch.length; 33 break 34 }else{ 35 lastidx = reg.lastIndex; 36 } 37 } 38 result.push(str.slice(lastidx)); 39 return result.join("") 40 } 41 })();
here is demo.