Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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).

like image 764
cdmckay Avatar asked Jul 06 '09 02:07

cdmckay


People also ask

What does \W in regex include?

\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.

What does $1 do in regex?

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.

What is $1 and $2 in JavaScript?

In the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern.

What does regex 0 * 1 * 0 * 1 * Mean?

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.


2 Answers

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

like image 175
Matthew Scharley Avatar answered Sep 23 '22 02:09

Matthew Scharley


/(\w)(\w)(\w)(\w)(\w)/.exec(undefined);   

returns: ["undef", "u", "n", "d", "e", "f"]

It is treating undefined as the string "undefined".

like image 25
user120242 Avatar answered Sep 21 '22 02:09

user120242