views:

91

answers:

3

The following code results in "undefined" for lastIndex:

var a = /cat/g;
var l = "A test sentence containing cat and dog.";
var r = a.exec(l);

document.write(r.lastIndex);

However, it works perfectly for r.index (and r.input).

I am using Firefox. Does anybody have a clue?

EDIT: OK, the above code works perfectly in IE! Further, in Firefox, it works perfectly if instead of calling r.lastIndex on line 5, a.lastIndex is called. It appears that Firefox does not return lastIndex property in the result - rather sets the property for the pattern invoking the exec() only. Interesting that IE sets both.

+3  A: 

lastIndex is a property of a RegExp object. So try this:

a.lastIndex
Gumbo
lastIndex is also a property of the result returned by exec() as well as a property of the pattern invoking the exec()
Crimson
@Crimson: No, `lastIndex` is not a property of the return value of `exec`: `r.hasOwnProperty("lastIndex")` returns *false*. See also https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp/exec#Description
Gumbo
+4  A: 

This is one of those places where Microsoft decided to add some stuff to the language and act as if it was supposed to be there. Thankfully, they are now cleaning up their act and documenting such nonsense.

To be clear: Firefox is correct according to the ECMAScript Language Specification 3rd Edition (PDF, 705KB).

IE is not correct; its behaviour is a proprietary extension. There is no reason to believe that this IE-specific behaviour will ever be supported by any other browser. It certainly isn't at the moment. See JScript Deviations from ES3 (PDF, 580KB, by Pratap Lakshman of Microsoft Corporation) Section 4.6 for more on this particular deviation from the spec, including tests showing no support on other browsers.

Note also that this may not even be supported in the future by IE: a number of proprietary IE CSS-related mechanisms are disabled by default on IE8-in-IE8-mode, and future implementations of JScript may find a reason to similarly disable this extension to the language.

NickFitz
A: 

To avoid all the weird, try this

var a = /cat/g;
var l = "A test sentence containing cat and dog.";
var r = a.exec(l);
var lastIndex = (r!=null) ? l.indexOf(r[0])+r[0].length : 0;

It is used here: http://www.pagecolumn.com/tool/regtest.htm

unigg