Note that there are some explanatory texts on larger screens.

plurals
  1. PORegex/lastIndex - Unexpected behaviour
    primarykey
    data
    text
    <p>I know there are a few regex/<strong><code>lastIndex</code></strong> discrepancies but this one is new to me!</p> <p><strong>Expected behaviour</strong>: Creating a new regular expression (with literal/constructor) will, obviously, create a new RegExp object with a <strong><code>lastIndex</code></strong> property set to zero.</p> <p><strong>Actual behaviour</strong>: (in FF, Chrome): The lastIndex property seems to persist through multiple RegExp creations. </p> <p>E.g.</p> <pre><code>function foo(s) { // A *NEW* regular expression // is created on each call of foo(): var regex = /ABC/g; document.write( regex.lastIndex + '&lt;br/&gt;' ); // regex.test() updates lastIndex property regex.test(s); // This is where the regex's life should end... // (Why does it persist?) } foo('ABC'); foo('ABCABC'); foo('ABCABCABC'); </code></pre> <p>See here: <strong><a href="http://jsbin.com/otoze" rel="nofollow noreferrer">http://jsbin.com/otoze</a></strong></p> <hr> <p>A new RegExp object is being created on every function call (right?), so why is the following being written to the document?? - </p> <pre><code>0 3 6 </code></pre> <p>???</p> <p>Note, this weirdness appears to happen in FF(3) and Chrome(2), but, curiously not IE.</p> <p>Is this expected behaviour, does IE get it wrong or right? Is this a well-known bug?</p> <hr> <p>EDIT: this doesn't appear to happen when instantiating the regex with a constructor instead of a literal. E.g. <strong><code>new RegExp('ABC','g');</code></strong> ... Still, the literal should (theoretically) work, right?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload