undefined cast to a string with regex test

# gaz Heyes (13 years ago)

This wasn't totally unexpected but seriously made me go WTF. It appears that arguments to regexp.test are cast to a string. This was bad for me since I was writing a js parser at the time and checking the argument to see if it matched one of the reserved words. See the example below:-

if(/^(?:undefined|ok|wtf|js)$/.test(undefined)){ alert('WTF'); } else { alert('NO WTF'); }

That's pretty much all I got but if you didn't go WTF then I apologise for the wasted thread.

# Rick Waldron (13 years ago)

On Wednesday, October 10, 2012 at 6:19 AM, gaz Heyes wrote:

This wasn't totally unexpected but seriously made me go WTF. It appears that arguments to regexp.test are cast to a string. This was bad for me since I was writing a js parser at the time and checking the argument to see if it matched one of the reserved words. See the example below:-

if(/^(?:undefined|ok|wtf|js)$/.test(undefined)){ alert('WTF'); } else { alert('NO WTF'); }

This is by design and surely not a wtf. test() is specified to accept and operate on a string argument and therefore coerces it's arg to a string.

This is very common throughout ES