Main Page

Opera has sup-ported regular expressions

The first step is to define a variable to hold the Opera version called
fOperaVersion
. Then, you can test
to see if Opera is using a disguise. If it isn’t, then just assign
fAppVersion
to
fOperaVersion
:
if (isOpera) {
var fOperaVersion;
if(navigator.appName == “Opera”) {
fOperaVersion = fAppVersion;
}
}
The more difficult case is when Opera is using a disguise. For this, you need to use the user-agent string
and extract the version by using a regular expression:
var reOperaVersion = new RegExp(“Opera (\\d+\\.\\d+)”);
This regular expression captures the Opera version, which is one or more numbers, followed by a deci-
mal point, followed by one or more numbers. Note that this regular expression uses the constructor
method and so
\d
and
\.
must be double escaped. The constructor method is used for backwards com-
patibility. Even if the browser proves not to be Opera and this code isn’t executed, it may not support the
regular expression literal style (which breaks ECMAScript Edition 1 syntax). This may cause an error.
Using this regular expression with the
test()
method stores the version in
RegExp.$1
, which is repre-
sented as
RegExp[“$1”]
to ensure it won’t break old-style JavaScript syntax.
if (isOpera) {
var fOperaVersion;
if(navigator.appName == “Opera”) {
fOperaVersion = fAppVersion;
} else {
var reOperaVersion = new RegExp(“Opera (\\d+\\.\\d+)”);
reOperaVersion.test(sUserAgent);
fOperaVersion = parseFloat(RegExp[“$1”]);
}
}
At this point, the version of Opera is contained in
fOperaVersion
. The only thing left is to fill in the
variables:
if (isOpera) {
var fOperaVersion;
if(navigator.appName == “Opera”) {
fOperaVersion = fAppVersion;
} else {
var reOperaVersion = new RegExp(“Opera (\\d+\\.\\d+)”);
reOperaVersion.test(sUserAgent);
fOperaVersion = parseFloat(RegExp[“$1”]);
}
It’s okay to use regular expressions inside this if statement because Opera has sup-
ported regular expressions almost before 4.0, the earliest version this script will detect.
238
Chapter 8
11_579088 ch08.qxd 3/28/05 11:38 AM Page 238


JavaScript EditorFree JavaScript Editor     Ajax Editor


©