Victor Grey Victor Grey - 4 months ago 16
Javascript Question

Javascript regex test weirdness

Can anyone explain this (using node version 4.2.4 repl)?

var n; //undefined
/^[a-z0-9]+$/.test(n); // true!
/^[a-f0-9]+$/.test(n); // false

Answer

Probably it's converting undefined to a string. So:

var pattern1 = /^[a-z0-9]+$/  
var pattern2 = /^[a-f0-9]+$/  
pattern1.test("undefined") // There are only letters  
pattern2.test("undefined") // defed match, but unin does not. 
Comments