nsIVersionComparator

This interface is used to compare version strings.
1.0
30
Introduced
Gecko 1.8
Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0)

Version strings are dot-separated sequences of version-parts. A version-part consists of up to four parts, all of which are optional:

<number-a><string-b><number-c><string-d (everything else)>

A version-part may also consist of a single asterisk "*" which indicates * "infinity". Numbers are base-10, and are zero if left out. Strings are compared bytewise.
For additional backwards compatibility, if "string-b" is "+" then "number-a" is incremented by 1 and "string-b" becomes "pre".

1.0pre1
  < 1.0pre2 
    < 1.0 == 1.0.0 == 1.0.0.0
      < 1.1pre == 1.1pre0 == 1.0+
        < 1.1pre1a
          < 1.1pre1
            < 1.1pre10a
              < 1.1pre10

Implemented by: @mozilla.org/xpcom/version-comparator;1. The service can be accessed directly via Services.vc after loading Services.jsm or with the following code:

var versionComparator = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
                                  .getService(Components.interfaces.nsIVersionComparator);

Method overview

long compare(in ACString A, in ACString B);

Methods

compare()

Compare two version strings.

long compare(
  in ACString A,
  in ACString B
);
Parameters
A
The first version.
B
The second version.
Return value

If A and B are two version being compared, and the return value

  • is smaller than 0, then A < B
  • equals 0 then Version, then A==B
  • is bigger than 0, then A > B

Example

function compareVersions(a,b) {
 var x = Services.vc.compare(a,b);
 if(x == 0)
   return a + "==" + b;
 else if(x > 0)
   return a + ">" + b;
 return a + "<" + b;
}
dump(compareVersions("1.0pre", "1.0"));

Example - Compare current browser version

This example here uses nsIXULAppInfo component to get the version of the browser that the code is running in. See here: nsIXULAppInfo

Components.utils.import("resource://gre/modules/Services.jsm");
var curentBrowserVersion = Services.appinfo.platformVersion; //example: '31.*'
var compareToThisVersion = '25.*';
var compareResult = Services.vc.compare(curentBrowserVersion, compareToThisVersion);

if (compareResult == -1) {
    //currentBrowserVersion is less than '25.*' (compareToThisVersion)
} else if (compareResult == 0) {
    //currentBrowserVersion is '25.*' (compareToThisVersion)
} else if (compareResult == 1) {
   //currentBrowserVersion is greater than '25.*' (compareToThisVersion)
} else {
   //will never get here as Services.vc.compare only returns -1, 0, or 1
}

See also

Document Tags and Contributors

 Contributors to this page: Noitidart, Sheppy, kmaglione, mnoorenberghe, trevorh, Smi, Nickolay
 Last updated by: Noitidart,