String#replace String#match and regexp.lastIndex

Steve L. steves_list at
Thu Jul 2 03:59:23 PDT 2009

It may be beneficial to clarify in the ES5 spec that searches should take 
place and lastIndex should be updated based on a copy of the value of 
lastIndex made at the start of String#replace's processing. If you follow 
the dependency chain--where String#replace relies on the definition of 
String#match, which in turn relies on RegExp#exec--it looks to me like the 
spec requires this code to become an infinite loop:

var str="0x2x3", a=["x","y","z"], i=0, re=/x/g;
alert(str.replace(re, function(){
    re.lastIndex = 0;
    return a[i++];

However, it is not an infinite loop in 5 out of 5 browsers. It should also 
be unambiguous that this would alert "0x2y3" (as it does in all the big 
browsers) and not "0y2z3".

While we're discussing String#replace, is it too late to formally spec what 
$n and $nn in replacement strings should mean when n is greater than the 
number of capturing groups within the regex? ES 3 & 5-draft say this is 
implementation-defined. Firefox 3.5, IE 8, Safari 4, Chrome 2, Opera 9.64, 
and all other browsers I've tested with say that e.g. "test".replace(/(e)/, 
"$2") returns "t$2st". I rely on this behavior, and I may not be the only 

Steven Levithan
Baghdad, Iraq

More information about the es-discuss mailing list