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
If you do not care about the .5.6, use parseInt
var majorV = parseInt("1.5.6",10)
Since you said you care about the minor versions:
function cmpVersion(v1, v2) {
if(v1===v2) return 0;
var a1 = v1.toString().split(".");
var a2 = v2.toString().split(".");
for( var i = 0; i < a1.length && i < a2.length; i++ ) {
var diff = parseInt(a1[i],10) - parseInt(a2[i],10);
if( diff>0 ) {
return 1;
}
else if( diff<0 ) {
return -1;
}
}
diff = a1.length - a2.length;
return (diff>0) ? 1 : (diff<0) ? -1 : 0;
}
console.log( cmpVersion( "1.0", "1.56") );
console.log( cmpVersion( "1.56", "1.56") );
console.log( cmpVersion( "1.65", "1.5.6") );
console.log( cmpVersion( "1.0", "1.5.6b3") );