Javascript – Getting RegExp result after being used in if-statement

javascriptregex

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?

Best Solution

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)