views:

353

answers:

3

Why does the the RegExp /^\w+$/ match undefined?

Example code:

alert(/^\w+$/.test(undefined));

This will display true in Firefox 3 (only browser I tested it on).

+15  A: 

When undefined is cast to a string (which the regex does), it produces the string "undefined", which is then matched.

Matthew Scharley
Makes sense, although it's a bit unintuitive.
cdmckay
Perhaps a little... but there's no real concept of exceptions or anything like that in JavaScript, a little quirky behaviour is better than dieing silently.
Matthew Scharley
Well there are Errors (https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Error)...
cdmckay
In my (admittedly, rather limited) experience though, they aren't all that much use in most cases...
Matthew Scharley
+2  A: 

/(\w)(\w)(\w)(\w)(\w)/.exec(undefined);
returns: ["undef", "u", "n", "d", "e", "f"]

It is treating undefined as the string "undefined".

+2  A: 

See ECMAScript Specification section 15.10.6.2 for RegExp.prototype.exec(string) which will be called from .match method. match basically is exec when it's evaluated to true.

Here is word for word from the specification: Performs a regular expression match of string against the regular expression and returns an Array object containing the results of the match, or null if the string did not match The string ToString(string) is searched for an occurrence of the regular expression pattern as follows:

  1. Let S be the value of ToString(string).
  2. Let length be the length of S.
  3. Let lastIndex be the value of the lastIndex property.
  4. Let i be the value of ToInteger(lastIndex).
  5. If the global property is false, let i = 0.
  6. If I < 0 or I > length then set lastIndex to 0 and return null.
  7. Call [[Match]], giving it the arguments S and i. If [[Match]] returned failure, go to step 8; otherwise let r be its State result and go to step 10.
  8. Let i = i+1.
  9. Go to step 6.
  10. Let e be r's endIndex value.

As you can see it will translate any input to a string, so undefined becomes 'undefined' and that will match to true.

Tested this as well outside the browser using JScript in command line and getting the same result.

Jimmy Chandra