String#replace String#match and regexp.lastIndex

John-David Dalton john.david.dalton at
Wed Jul 1 07:28:16 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.
Currently Firefox, Chrome, Safari, Opera do not set the lastIndex on
String#match 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

This might be a compatibility issue to consider.

- John-David Dalton

More information about the es-discuss mailing list