8 Replies Latest reply on Jun 5, 2011 11:17 AM by Peter Kahrel

    [JS] Beware of String.search(RegExp)

    Marc Autret Level 4

      Hi all,

       

      According to ECMA-262, String.prototype.search(RegExp) shouldn't change the lastIndex property of the regexp. But it seems that ExtendScript does not apply this rule, so we have a very unexpected behavior as shown in the the following example:

       

       

      var reg = /bar/;
      alert( 'foobar'.search(reg) );          // => 3
      alert( 'foobar'.search(reg) );          // => -1 !
      

       

      The second search(…) fails because reg.lastIndex has been modified during the first call.

       

      This bug (?) may be really harmful If you're used to 'precompile' your regex for optimization purpose:

       

      var reg = /bar/;
      var myString;
      
      while( . . . )
           {
           . . .
           
           myString.search(reg);     // will only work the first time!
           
           . . .
           }

       

      You can fix this issue by inserting reg.lastIndex = 0; before each call to the search() method.

       

      @+

      Marc