Skip to content

Instantly share code, notes, and snippets.

@omni5cience
Created May 21, 2015 03:28
Show Gist options
  • Save omni5cience/04252f228b322d5c9a50 to your computer and use it in GitHub Desktop.
Save omni5cience/04252f228b322d5c9a50 to your computer and use it in GitHub Desktop.
Wat
var wat = /.+/g;
wat.test(undefined); // true
wat.test(undefined); // false
wat
@omni5cience
Copy link
Author

I forgot to update this at the time, but the answer is that global RegExps (i.e. those with /g) are stateful.
We can observe this by looking at wat.lastIndex.

var wat = /.+/g;
wat.lastIndex === 0; // It starts at 0, i.e. the start of the string

wat.test(undefined); // true, because undefined will be coerced to the string 'undefined'
                     // and 'undefined' matches . at least once

'undefined'.length === 9;
wat.lastIndex === 9; // Now we're at 9, (i.e. the end of the "string" we tested)

wat.test(undefined); // false, because '' (empty string) doesn't match . at least once
wat.lastIndex === 0; // Since it wrapped around, lastIndex was reset

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment