I have 2 strings in javascript that contain numeric numbers which represent file version.
i.e
var str1 = "11.11.1111.1111"
var str2 = "11.22.3333.5555"
How can i perform numeric comparison between them?
I would like to check if str1 > str2
I have 2 strings in javascript that contain numeric numbers which represent file version.
i.e
var str1 = "11.11.1111.1111"
var str2 = "11.22.3333.5555"
How can i perform numeric comparison between them?
I would like to check if str1 > str2
As long as str1 and str2 are guaranteed to be the same length and format, just do str1 > str2
. String comparison is lexicographical (compare the first character of both, the second character of both... and return the value of the first difference), and for two equal length numbers/number-like strings that gives you exactly what you want.
If they are not guaranteed to be the same, try splitting by .
, converting each string part to int and comparing them int-wise one by one until you find a difference.
You could go for:
var str1 = '11.11.1111.1111'
,str2 = '11.22.3333.5555'
,compare = str1.split('.')
.map(function(a) {
return +a > +(this.splice(0,1));
},
str2.split('.'))
.reduce(function(a,b){return a||b;});
//=> compare now: false