Skip to content

Instantly share code, notes, and snippets.

@jgillman
Last active January 3, 2016 23:29
Show Gist options
  • Save jgillman/8535512 to your computer and use it in GitHub Desktop.
Save jgillman/8535512 to your computer and use it in GitHub Desktop.
A node script with confusing output.
var re = /s\d{2}/i;
var reGlobal = /s\d{2}/gi;
var string = 's05';
console.log( 'Testing reGlobal 4 times:' );
console.log( reGlobal.test(string) );
console.log( reGlobal.test(string) );
console.log( reGlobal.test(string) );
console.log( reGlobal.test(string) );
console.log( '\nTesting re 4 times:' );
console.log( re.test(string) );
console.log( re.test(string) );
console.log( re.test(string) );
console.log( re.test(string) );
Testing reGlobal 4 times:
true
false
true
false
Testing re 4 times:
true
true
true
true
@jgillman
Copy link
Author

Got an answer on Freenode #Node.js:

ljharb: regexes retain an internal position flag
ljharb: if instead of caching the regex, you use a literal every time, it will never be different.
ljharb: i believe you can also just explicitly set lastIndex to 0 before each check
ljharb: but i doubt that's any faster than just a bunch of literals

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