In any kind of development, you often have to deal with version strings. Typically, these version strings are just a dot-separated list of numbers that represent different versions of the software. I recently had a need to compare two version numbers against one another to determine which one was newer. This is useful if, say, you’re building an application that wants to check its current version against the “latest” available version.
In JavaScript, this is thankfully pretty trivial. My solution is to just parse the version strings with a simple function and return them as objects with appropriate properties whose values are integers. Once in this form, we can compare them with simple math.
function parseVersionString (str) {
if (typeof(str) != 'string') { return false; }
var x = str.split('.');
// parse from string or default to 0 if can't parse
var maj = parseInt(x[0]) || 0;
var min = parseInt(x[1]) || 0;
var pat = parseInt(x[2]) || 0;
return {
major: maj,
minor: min,
patch: pat
}
}
Using this new object, we can now compare two versions really simply:
var running_version = parseVersionString('3.5.2');
var latest_version = parseVersionString('3.4.5');
if (running_version.major < latest_version.major) {
// A major new update is available!
} else if (running_version.minor < latest_version.minor || running_version.patch < latest_version.patch) {
// A new minor or patch update is available.
} else {
// We are running the latest version! No need to update.
}
Thanks, saved me some time
zch
8 Jun 09 at 2:23 PM
Thanks for this object parser! Saved me some time as well.
For anyone looking for a minimum version requirement met function that returns a Boolean, something like this should work:
Jesse Silverstein
30 May 10 at 8:31 AM
Nice function. Tightened it up a bit by using regex and combined it with the comment above. Hope this helps.
var versionCompare = function(minimum, current) {
var minimum = ” + minimum; // Convert number to string
var current = ” + current;
var parseVersion = function(version) {
version = /(\d+)\.?(\d+)?\.?(\d+)?/.exec(version);
return {
major: parseInt(version[1]) || 0,
minor: parseInt(version[2]) || 0,
patch: parseInt(version[3]) || 0
}
};
minimum = parseVersion(minimum);
current = parseVersion(current);
if (minimum.major != current.major)
return (current.major > minimum.major);
else {
if (minimum.minor != current.minor)
return (current.minor > minimum.minor);
else {
if (minimum.patch != current.patch) {
return (current.patch > minimum.patch);
}
else {
return true;
}
}
}
};
Mark Carver
17 Jul 10 at 2:00 PM