Question

I am trying to figure out how to detect the browser versions of a browser for website support reasons. I want to know if the browser is great than say 3.6.1 then the browser is ok, else show an error.

The problem is that I can only do this with 1 decimal place, there must be a way to do this.

I have tried parseFloat("3.6.28") but it just gives me 3.6.

How can I do this:

if(3.5.1 > 3.5.0)
{
//Pass!
}
Was it helpful?

Solution

If you'll be working with versions a lot it might be worth writing something like this

function Version(str) {
    var arr = str.split('.');
    this.major    = +arr[0] || 0;
    this.minor    = +arr[1] || 0;
    this.revision = +arr[2] || 0; // or whatever you want to call these
    this.build    = +arr[3] || 0; // just in case
    this.toString();
}
Version.prototype.compare = function (anotherVersion) {
    if (this.toString() === anotherVersion.toString())
        return 0;
    if (
        this.major > anotherVersion.major ||
        this.minor > anotherVersion.minor ||
        this.revision > anotherVersion.revision ||
        this.build > anotherVersion.build
    ) {
        return 1;
    }
    return -1;
};
Version.prototype.toString = function () {
    this.versionString = this.major + '.' + this.minor + '.' + this.revision;
    if (this.build)
        this.versionString += '.' + this.build;
    return this.versionString;
};

Now

var a = new Version('3.5.1'),
    b = new Version('3.5.0');
a.compare(b); //  1 , a is bigger than b
b.compare(a); // -1 , b is smaller than a
a.compare(a); //  0 , a is the same as a

Otherwise just use the bits you need

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top