Main Page

compareVersions

A common occurrence in user-agent strings is a version number with multiple decimal points (for exam-
ple, Mozilla 0.9.2). This causes a problem when you are trying to compare browser versions. You already
know that the
parseFloat()
function is used to convert a string into a floating-point number. In addi-
tion,
parseFloat()
works by going character-by-character through a string, stopping when it finds a
non-number
character. In the case of a version number with multiple decimal points, the non-number
character is the second decimal point. That means using
parseFloat()
on the string
“0.9.2”
yields
a floating-point value of
0.9
, completely losing
.2
. That’s not good.
The best method for comparing two versions of this type of string is to compare the value after the deci-
mal point in each. For instance, suppose you want to determine whether 0.9.2 is greater than 0.9.1. The
correct way to do this is to compare 0 to 0, 9 to 9, and 2 to 1. Because 2 is greater than 1, version 0.9.2 is
greater than 0.9.1. Because you perform this operation so often when detecting browser and operating
system versions, it’s logical to encapsulate this logic in a function.
The function
compareVersions()
accept two string versions as arguments and returns 0 if they are
equal, 1 if the first version is greater than the second, and –1 if the first version is less than the second.
(As you saw earlier in this book, this is a very common way of representing the relationship between
two versions.)
The first step in the function is to convert each version into an array of values. This fastest way to do this
is to use the
split()
method and pass in the decimal point as the character separator:
function compareVersions(sVersion1, sVersion2) {
var aVersion1 = sVersion1.split(“.”);
var aVersion2 = sVersion2.split(“.”);
}
At this point,
aVersion1
contains the numbers for the first version passed in, and
aVersion2
contains
the number of the last version passed in. Next, it is necessary to assure that the arrays have the same
number of digits; otherwise, it is very difficult to compare 0.8.4 to 0.9. To do this, first determine which
array has more digits, and then add zeroes to the other array. This results in 0.9 becoming 0.9.0.
function compareVersions(sVersion1, sVersion2) {
var aVersion1 = sVersion1.split(“.”);
var aVersion2 = sVersion2.split(“.”);
if (aVersion1.length > aVersion2.length) {
for (var i=0; i < aVersion1.length - aVersion2.length; i++) {
aVersion2.push(“0”);
}
} else if (aVersion1.length < aVersion2.length) {
for (var i=0; i < aVersion2.length - aVersion1.length; i++) {
aVersion1.push(“0”);
}
}
}
235
Browser and Operating System Detection
11_579088 ch08.qxd 3/28/05 11:38 AM Page 235


JavaScript EditorFree JavaScript Editor     Ajax Editor


©