Should regexp.lastIndex be incremented after zero-length matches?

Steven L. steves_list at hotmail.com
Tue Jul 8 17:43:41 PDT 2008


Internet Explorer increments the lastIndex of a regexp with /g after matching a zero-length string using exec or test. This helps avoid infinite loops and therefore brings regular expression usage in line with other programming languages and regex libraries, as well as developer expectations (there is some evidence of this at https://bugzilla.mozilla.org/show_bug.cgi?id=252356 ). IE's behavior also seems in line with ES3 15.10.7.5, which states that "The value of the lastIndex property is an integer that specifies the string position at which to start the next match."

Granted, the property is named lastIndex, and not nextStartIndex or some such. But then section 15.10.7.5 does not agree with the name of the property. Is lastIndex the end of the last match, or the beginning of the wrong place to start the next match?

Here is an example of when one must go out of their way to avoid an infinite loop that would result from the ES3 standard behavior:

var regex = /^/gm, str = "test", match;
while (match = regex.exec(str)) {
    ...
    if (regex.lastIndex == match.index) regex.lastIndex++;
}

Or, if one wishes their code to access a lastIndex value as described in ES3 cross-browser:

var regex = /^/gm, str = "test", match;
while (match = regex.exec(str)) {
    if (!match[0].length && regex.lastIndex > match.index) regex.lastIndex--;
    ...
    if (regex.lastIndex == match.index) regex.lastIndex++;
}

Changing the handling of lastIndex to match IE (incrementing after zero-length matches) might break some programs. IMO, it would equally likely fix some programs that are currently susceptible to infinite loops or other unexpected behavior.

--Steven Levithan



_________________________________________________________________
It’s a talkathon – but it’s not just talk.
http://www.imtalkathon.com/?source=EML_WLH_Talkathon_JustTalk
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.mozilla.org/pipermail/es-discuss/attachments/20080708/c1388734/attachment-0002.html 


More information about the Es4-discuss mailing list