Odd behavior replacing string with special replacement patterns in IE7 | eight

I discovered a very strange problem in IE7 | 8 when using special replacement patterns:

'moo$$e'.replace( /\$/g, '$$$$' ); 'moo$$e'.replace( '\$', '$$$$', 'g' ); 

Latest Chrome:

  moo$$$$e moo$$$e 

Latest Firefox:

  moo$$$$e moo$$$$e 

IE7 | eight:

  moo$$$$e moo$$$$$e 

I know that the parameter is not standard , therefore, the difference between Firefox and Chrome in the second case. I like it .

However, what I see in IE7 | 8, really odd (second case). I tried playing with '\x24' , slipping and stuff, but I can't find a way to work as expected ( $$ means $ ).

I know that this can be easily done with split() and join() , for example:

 'moo$$e'.split( '$' ).join( '$$' ); > "moo$$$$e" 

but I'm really very interested in that with IE. Is there any explanation?

See a live example .

+4
source share
1 answer

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.

+3
source

Source: https://habr.com/ru/post/1482982/


All Articles