Closed Bug 296610 Opened 19 years ago Closed 19 years ago

Javascript .exec gives 'no properties' when in loop for every 2nd round, with option 'g'

Categories

(Core :: JavaScript Engine, defect)

x86
Windows XP
defect
Not set
normal

Tracking

()

RESOLVED DUPLICATE of bug 98409

People

(Reporter: chayes, Unassigned)

Details

User-Agent:       Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8b2) Gecko/20050603
Build Identifier: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8b2) Gecko/20050603

This is a pretty specific error I ran into.

Running the following regexp gives back an array with matches, or empty.
 var matches = /td/gi.exec(str);
Running this line several times OUTSIDE a loop (by copying the content) also
works as expected. 

But when it is enclosed in a loop (for or while), every second run through the
loop results in (JS console: 'Error: matches has no properties') when trying to
access the result. The script stops at this error. 

This error seems to occur only with the 'g' option, and within loops. 

The error was found in Firefox 1.0.4, but confirmed in Mozilla Suite. No error
occurred in IE. 

[I do not think the regexp itself or the text string have anything to do with
the problem.]

Reproducible: Always

Steps to Reproduce:
1. Run this script:
<script>
var str= 'begin <td class="window_title">Bla bla</td> end';

for (var nr=1;nr<=5 ;nr++)
{ var matches = /td/g.exec(str);
  alert('Run '+nr+' on '+matches[0]+':'+matches.join('/'));
}
</script>

Actual Results:  
First time: ok.
Second time: error.Error: matches has no properties. Script stops.
------------
When the alert is wrapped in 
if (matches) {alert(...)}
i see that the 3rd,5th, 7th time the matches are ok, but not the 2nd, 4th, 6th time.

Expected Results:  
Give the matches array every time, even if there are no results.

Since it occurs in Mozilla as well as Firefox, and is so specific, I assume my
extensions (GreaseMonkey and others) are not relevant.
Summary: Javascript .exec gives 'no properties' when in loop for every 2nd round, with option 'g' → Javascript .exec gives 'no properties' when in loop for every 2nd round, with option 'g'
Version: unspecified → Trunk
note that bugs that occur in both firefox and the suite generally belong to the
Core product.
Assignee: general → general
Component: General → JavaScript Engine
Product: Mozilla Application Suite → Core
QA Contact: general → general

*** This bug has been marked as a duplicate of 98409 ***
Status: UNCONFIRMED → RESOLVED
Closed: 19 years ago
Resolution: --- → DUPLICATE
Oh, thanks, I thought I was smart but I wasn't :-}.

Most tutorials fail to mention this, unfortunately. On
http://www.js-examples.com/javascript/ref_js15/regexp.php
I found out how to reset the lastIndex. I'm posting it just in case it helps
someone...

 MyRegExp=/abc/gi;
 MyRegExp.lastIndex=0;
 var matches = MyRegExp.exec(str);
You need to log in before you can comment on or make changes to this bug.