Victor Grey
Victor Grey

Reputation: 941

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

Upvotes: 0

Views: 63

Answers (3)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

RegExp.test treats n as a string "undefined".
So, the range [a-f] does not cover all the characters of undefined string.
In your case, the "mimimum allowable" range for passing regexp check would be [a-u]

var n; //undefined
console.log(/^[a-u]+$/.test(n));   // true

Upvotes: 0

slebetman
slebetman

Reputation: 113866

The variable passed to .test() is first converted to string. This is specified in the spec:

http://www.ecma-international.org/ecma-262/5.1/#sec-15.10.6.3

which points to:

http://www.ecma-international.org/ecma-262/5.1/#sec-15.10.6.2

which says:

  1. Let R be this RegExp object.
  2. Let S be the value of ToString(string).

So basically you're testing:

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

It should now be obvious why the second test returns false. The letters u, n and i are not included in the test pattern.


Note: The function ToString() in the spec refers to the type coercion function in the underlying implementation (most probably C or C++ though there exist other implementations of js in other languages like Java and Go). It does not refer to the global function toString() in js. As such, that second line in the spec basically means that undefined will be treated as "" + undefined which returns "undefined".

Upvotes: 1

user6597761
user6597761

Reputation:

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. 

Upvotes: 1

Related Questions