String#replace String#match and regexp.lastIndex

Steve L. steves_list at hotmail.com
Wed Jul 1 10:08:35 PDT 2009


> I noticed in the ECMA 5 draft that String#replace references
> String#match's handling of regexp.lastIndex
> when the regexp is flagged global. According to the draft String#match
> sets the regexp.lastIndex when the regexp is global.

All of this is identical to ECMA-262 Edition 3.

> Currently Firefox, Chrome, Safari, Opera do not set the lastIndex on
> String#match

Yes they do. Leaving aside whatever happens during the matching process 
(since it's unobservable to users), String#match called with a "global" 
RegExp always starts searching from index 0 and the RegExp's lastIndex is 
always 0 after after the method is complete. (That is, except in IE, which 
has the bug you mentioned where lastIndex is not always 0 after a match or 
replace using a "global" regex is complete.)

This should alert 0, demonstrating that the browsers you mentioned do update 
lastIndex:

var x = /x/g;
x.lastIndex = 1;
"x123x5".match(x);
alert(x.lastIndex);

> or String#replace.
> IE does set the lastIndex but only once, not during each internal
> iteration of `Repeat, while lastMatch is true`, and for non-global
> regexp's as well.
>
> According to spec I would expect:
>
> var s = '0x2x4x6x8';
> var p = /x/g;
> s.replace(p, function() { alert(p.lastIndex)  }); // A: alerts 2, then
> 4, then 6, then 8
> alert(p.lastIndex); // B: alerts 0 because internal exec returned null
> (which set lastIndex 0) triggering the end of the iteration;
>
> // IE7
> // A: alerts 0, then 0, then 0, then 0
> // B: alerts 8
>
> // All others
> // A: alerts 0, then 0, then 0, then 0
> // B: alerts 0

Opera 9.64 (and other versions I've previously tested this issue with) 
alerts A: 2, 4, 6, 8 and B: 0. Like you, this is my interpretation of 
correct handling according to the spec. Opera tends to follow the spec most 
closely for regex issues, in general.

> This might be a compatibility issue to consider.

Sure, but it's a decade old.

Steve
--------------------
Steven Levithan
Baghdad, Iraq
http://blog.stevenlevithan.com
 



More information about the es-discuss mailing list