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

Martin Wheeler @martinwheeler

About: I'm a front end developer working in the land of React. Just starting to get my hands on TS.

Location:
Melbourne
Joined:
Jul 28, 2019

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

Publish Date: Sep 16 '19
3 0
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.

Comments 0 total

    Add comment