views:

96

answers:

2

I've seen people do the following:

if (/Firefox\/(\+S)/.test(userAgent)) {
    firefox = RegExp.$1;
}

I know (sorta) what the regexp does, but I'm not really sure how it can be accessed with RegExp.$1.

And as a side note:

if (/Win(?:dows )?([^do]{2})\s?(\d+\.\d+)?/.test(ua)) {
 if (RegExp.$1 == "NT") {
  switch (RegExp.$2) {

What's the difference between $1 and $2?

+4  A: 

What's the difference between $1 and $2?

Those are the references to the captured groups (captured by the regexp)

The JavaScript flavor of regex refers to group #1 as $1, and group #2 as $2.

 Win(?:dows )?([^do]{2})\s?(\d+\.\d+)?
     ^         ^            ^
     |         |            |
     |         group#1      group#2
     |
     ignored group (?: means non-capturing)
VonC
nice diagram, and nice link (:thanks
peirix
A: 

RegExp is a global object that is updated every time a RegExp is run. RexExp.$1 will contain the text matched by the corresponding set of parentheses in the last pattern matched.

For the sidenote: $1 contains is the first part of the regexp between the parentheses, $2 the seconds etc...

ylebre