DEV Community

Martin Wheeler
Martin Wheeler

Posted on

TIL: RegExp global flag doesn't return what you'd expect

const myRegExp = /[0-9]+ [a-z]+ [a-z]+/gi
const myString = '10 Banana Road'

const doesItMatch = myRegExp.test(myString)
// true
const itShouldMatch = myRegExp.test(myString)
// false

Wait, what?!? Why is it true and then false? What's going on here?

The answer isn't as intuitive as I first thought. This is what I found on stackoverflow: https://stackoverflow.com/a/1520853

Essentially the global flag is what's causing the issue. It appears to have some internal state which wasn't something I was aware of. Upon removing the global flag the tests will both return true.

Top comments (0)