ponyfoo.com

Are Regular Expressions Stateful?

Fix
A relevant ad will be displayed here soon. These ads help pay for my hosting.
Please consider disabling your ad blocker on Pony Foo. These ads help pay for my hosting.
You can support Pony Foo directly through Patreon or via PayPal.

I seem to have stumbled across a bug regarding regular expressions using the g modifier, where they seem to preserve internal state across calls to RegExp.prototype.test. I’m looking for confirmation or a “you’re stupid, this is what is going on” dismissal.

Apparently regular expressions with the g modifier are stateful. See for yourself.

<button id='bad'>Wait, WHAT?</button>
stateful = /button/ig;
bad.onclick = function (e) {
  alert(stateful.test(e.target.tagName));
};

The button alternates between alerting true and false in Google Chrome 38.0.2125.122, and also on Firefox 31.

As it turns out, this is the “expected” behavior. I did not expect that. Regular expressions with the g modifier on them will keep track of the lastIndex where a match occurred, even across calls to .test.

You can check out the live example on CodePen, too.

Liked the article? Subscribe below to get an email when new articles come out! Also, follow @ponyfoo on Twitter and @ponyfoo on Facebook.
One-click unsubscribe, anytime. Learn more.

Comments