Does anyone have code to compare two version numbers in JavaScript? I just want simple version comparisons (e.g. \"1.0\"
vs \"1.5.6\"
), and it shou
This function returns true if the version is greater than or equal to the minimum version. Assumes 1.0 is greater than 1 when versions are strings. When they are numbers it says they are the same. If you want to have both types return the same then you need to convert the numbers to strings which is also easy. or you can modify the string condition to check if the longer version number has all trailing zeros like 1.1 vs 1.1.0.0.0.0. the second one is all trailing zeros
function doesMyVersionMeetMinimum(myVersion, minimumVersion) {
if(typeof myVersion === 'number' && typeof minimumVersion === 'number') {
return(myVersion >= minimumVersion);
}
var v1 = myVersion.split("."), v2 = minimumVersion.split("."), minLength;
minLength= Math.min(v1.length, v2.length);
for(i=0; i<minLength; i++) {
if(Number(v1[i]) < Number(v2[i])) {
return false;
}
else if(Number(v1[i]) < Number(v2[i])) {
return true;
}
}
return (v1.length >= v2.length);
}
If you want to be fully correct, take a look at the discussion on PEP386, especially the heading “the new versioning algorithm”.
Otherwise it seems like your answer is pretty good.