JavaScript RegExp.exec() misbehaves - not updating lastIndex

RESOLVED DUPLICATE of bug 252356

Status

()

Firefox
General
RESOLVED DUPLICATE of bug 252356
11 years ago
11 years ago

People

(Reporter: Thomas_H, Unassigned)

Tracking

Firefox Tracking Flags

(Not tracked)

Details

Attachments

(1 attachment)

(Reporter)

Description

11 years ago
User-Agent:       Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3
Build Identifier: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3

The following code will go into an infinite loop, were it not for the counter that breaks the loop after 100 iterations.

I'm using a '/gm' regexp to iterate over a multi-line string (embedded '\n'). The problem is that on an empty line apparently the 'lastIndex' property of the regexp is not updated correctly. So it will re-match the empty line over and over again. On non-empty lines the match works as expected.


  <script type="text/javascript">
  var s = "this\nis text\nwith an empty\n\nline";
  var r = /^.*$/gm;
  var e;
  var i=0;

  // except for the running counter, this is basically Flanagan(5th), 691
  while ((e=r.exec(s)) != null)
  {
    if (++i > 100) { break; }
    alert(i+": \""+e[0]+"\" :(r.lastIndex: "+r.lastIndex+")<br>");
  }
  </script>



Reproducible: Always

Steps to Reproduce:
1. Put the above script on an HTML page.
2. Load the page in Firefox.
3.
Actual Results:  
FF goes into an infinite loop on the empty line in the string.

Expected Results:  
Proceed to the next line in the input string, incrementing the r.lastIndex.
(Reporter)

Comment 1

11 years ago
Created attachment 268346 [details]
Complete HTML page that shows the bug (using document.write()).

Comment 2

11 years ago
Duplicate of bug 252356 ?
(Reporter)

Comment 3

11 years ago
Gosh, you're right, and I'm embarrassed! Thanks for pointing this out. All I can say in my defense is that I, since Bugzilla search is so slow, narrowed my search to Firefox. I was sure that if this was a known bug there must be some hits within Firefox.

But I'm likewise astonished about how the original bug has been treated (RESOLVED INVALID). It's hard to believe this has not been fixed in 3 years, and just because the spec is flawed. This means you can never iterate through a string with a regexp to count the newlines. What a pitty. The behaviour is so obviously wrong that I can't think about it otherwise. How many people have fixed this in their own code?! Applying common sense and implementing the right behaviour seems like "The Right Thing" to do, rather than sticking to spec conformance at all costs, doesn't it?!

Maybe this bug raises some attention with the developers so they might re-think their decision.

=Thomas
Status: UNCONFIRMED → RESOLVED
Last Resolved: 11 years ago
Resolution: --- → DUPLICATE
Duplicate of bug: 252356
You need to log in before you can comment on or make changes to this bug.