Closed Bug 384418 Opened 17 years ago Closed 17 years ago

JavaScript RegExp.exec() misbehaves - not updating lastIndex

Categories

(Firefox :: General, defect)

x86
Linux
defect
Not set
normal

Tracking

()

RESOLVED DUPLICATE of bug 252356

People

(Reporter: thomas.bugzilla, Unassigned)

Details

Attachments

(1 file)

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.
Duplicate of bug 252356 ?
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
Closed: 17 years ago
Resolution: --- → DUPLICATE
You need to log in before you can comment on or make changes to this bug.

Attachment

General

Creator:
Created:
Updated:
Size: