<p>
Basic check to test if one version is same or above another version.<br>
<br>
Usually it is better do do feature detection, but sometimes it is handy to be able to compare versions.<br>
<br>
Also, sometimes a feature exists, but works slightly different in another version, then you might also need to check the version.<br>
</p>
e.g.
<pre>
if ($ && $f.fn && $.fn.on) { /* ... */ }
// vs
if ($ && $f.fn && $.fn.jquery && checkVersion('1.7.0', $.fn.jquery)) { /* ... */ }
</pre>
JavaScript
function checkVersion(v1, v2){
// check if v2 is equal or above v1
var v1_arr = (''+v1).split('.');
var v2_arr = (''+v2).split('.');
for (var i=0; i < v2_arr.length; i++) {
// parseInt() : so '12' > '2'
// || '0' : so missing version parts count as 0
var v1_i = parseInt(v1_arr[i] || '0', 10);
var v2_i = parseInt(v2_arr[i] || '0', 10);
if (v1_i > v2_i) {
// current v2 version part is bigger than it's counterpart in v1, no need to check any further and return true:
return true ;
}
if (v1_i < v2_i) {
// current v2 version part is smaller than it's counterpart in v1, no need to check any further and return false:
return false;
}
// if equal; continue to next part (if any)
}
// if we get here all parts are equal, return true:
return true ;
}
// [v1, v2, expected value]:
var tests = [
['1.2.3','1.2.3', true ],
['1.12.3','1.2.3', true ],
['1.2.3','1.12.3', false],
['1.2.3','1.2', true ],
['1.2','1.1.3', true ],
['1.2','1.2.3', false],
];
var test_results = [];
$.each(tests, function(i, t){
var r = checkVersion(t[0], t[1]);
test_results.push({
v1 : t[0],
v2 : t[1],
expected : t[2],
result : r,
correct : t[2]==r
});
});
console.table(test_results);
/*
(index) v1 v2 expected result correct
0 "1.2.3" "1.2.3" true true true
1 "1.12.3" "1.2.3" true true true
2 "1.2.3" "1.12.3" false false true
3 "1.2.3" "1.2" true true true
4 "1.2" "1.1.3" true true true
5 "1.2" "1.2.3" false false true
*/
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.