Test version
I looked at a test case with the results to present it as follows:
var results = [ 'YY'.replace( /Y/g, '$$' ), 'YY'.replace( 'Y', '$$', 'g' ), 'YY'.replace( 'Y', function( a, b ) { return '$$'; }, 'g' ), 'YY'.replace( /Y/g, function( a, b ) { return '$$'; }) ]; console.log( results.join( '\n' ) );
results
Chrome
$$ // '$$' -> '$', global flag used, every 'Y' -> '$' $Y // '$$' -> '$', global flag ignored, first 'Y' -> '$' $$Y // '$$' -> '$$', global flag ignored, first 'Y' -> '$$' $$$$ // '$$' -> '$$', global flag used, every 'Y' -> '$$'
Firefox
$$ // '$$' -> '$', global flag used, every 'Y' -> '$' $$ // '$$' -> '$', global flag used, every 'Y' -> '$' $$$$ // '$$' -> '$$', global flag used, every 'Y' -> '$$' $$$$ // '$$' -> '$$', global flag used, every 'Y' -> '$$'
IE7 and 8
$$ // '$$' -> '$', global flag used, every 'Y' -> '$' $$Y // '$$' -> '$$', global flag ignored, first 'Y' -> '$$' $$Y // '$$' -> '$$', global flag ignored, first 'Y' -> '$$' $$$$ // '$$' -> '$$', global flag used, every 'Y' -> '$$'
Conclusion
Chrome ignores the 'g' flag as the third String.replace parameter, since the flags used do not belong to any standard .
IE assumes $$ will be a string, not a substitute for control and ignore the global flag in this case:
'YY'.replace( 'Y', '$$', 'g' );
The simplest solution ensures that the results are always the same: use a RegExp object with flags ( /foo/flags ) as the first parameter and either a string or function as the second parameter.
If the string is the second parameter, $$ converted to $ . If it is a function-dependent replacement, there is no such conversion.