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).
\w (word character) matches any single letter, number or underscore (same as [a-zA-Z0-9_] ). The uppercase counterpart \W (non-word-character) matches any single character that doesn't match by \w (same as [^a-zA-Z0-9_] ). In regex, the uppercase metacharacter is always the inverse of the lowercase counterpart.
The $ number language element includes the last substring matched by the number capturing group in the replacement string, where number is the index of the capturing group. For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
In the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern.
Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1. 1* means any number of ones.
When undefined
is cast to a string (which the regex does), it produces the string "undefined"
, which is then matched.
/(\w)(\w)(\w)(\w)(\w)/.exec(undefined);
returns: ["undef", "u", "n", "d", "e", "f"]
It is treating undefined as the string "undefined"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With