What happens when null is passed to a JavaScript regular expression?

It’s quite possible that the following is not the expected consequence of passing null to a JavaScript regular expression — it certainly surprised me:

/null/.test(null)
// => true

It looks like extra intentional work is being done to convert the value null to the string “null” whereas my assumption was that, particularly as it’s falsy, it would be interpreted as a blank string.

What’s happening?

I was impressed at how easy it was to find the answer in the ECMA spec that defines this behaviour. It turns out that it is doing extra intentional work to convert null to the string “null”.

The spec also describes the following surprising (to me at least) cases:

/undefined/.test(undefined)
// => true

/true/.test(true)
// => true

/false/.test(false)
// => true

/\[object Object\]/.test({ a: 1 })
// => true

/1,2/.test([1, 2])
// => true

One example that does feel natural is converting a number to a string:

/123.45/.test(123.45)
// => true

But even this has some edge cases:

/Infinity/.test(1 / 0)
// => true

/NaN/.test(0 / 0)
// => true

Back to my problem, what’s the fix?

I could imagine this introducing a type of Scunthorpe problem — albeit with a relatively small window of opportunity — and for the non-falsy cases is the sort of issue that a type-checking system like Flow could help mitigate. Fortunately in my case the value was either a string or null so it was enough to default to an empty string:

var value = null
/null/.test(value || '')
// => false

Originally published at www.benpickles.com