Version compare
Returns: 0: a = b 1: a > b -1: a < b https://stackoverflow.com/questions/6832596/how-can-i-compare-software-version-number-using-javascript-only-numbers/53387532#
by vanowm
HTML
<div id="eb">
<span>
<div id="e"></div>
<div id="i">
<span>
<span><input id="a" oninput="check()"></span>
<span id="r">?</span>
<span><input id="b" oninput="check()"></span>
</span>
</div>
</span>
<span>
<div id="er"></div>
<div id="rb">
<input type="button" onclick="showRand()" value="Refresh">
</div>
</span>
</div>
CSS
#a
{
text-align: end;
}
input
{
width: 13ch;
}
div[id]
{
display: table;
border-collapse: collapse;
}
div[id] > div
{
display: table-row;
border: 1px solid black;
}
#i > span
{
display: inline-block;
}
#eb > span,
#e span,
#er span
{
padding: 0 0.2em;
display: table-cell;
}
#r,
#e span:nth-of-type(2),
#er span:nth-of-type(2)
{
padding: 0.1em 0.2em;
}
#i,
#rb
{
margin: 0.3em 0;
display: block;
padding: 0;
text-align: center;
}
.new
{
background-color: lightgreen;
}
.old
{
background-color: lightpink;
}
.same
{
background-color: lightblue;
}
JavaScript
/*use strict*/
const compareVersions = ((prep, l, i, r) => (a, b) =>
{
a = prep(a);
b = prep(b);
l = Math.max(a.length, b.length);
i = 0;
r = i;
while (!r && i < l)
//convert into integer, including undefined values
r = ~~a[i] - ~~b[i++];
return r < 0 ? -1 : (r ? 1 : 0);
})(t => ("" + t)
// treat non-numerical characters as lower version
// replacing them with a negative number based on charcode of first character
.replace(/[^\d.]+/g, c => "." + (c.replace(/[\W_]+/, "").toUpperCase().charCodeAt(0) - 65536) + ".")
// remove trailing "." and "0" if followed by non-numerical characters (1.0.0b);
.replace(/(?:\.0+)*(\.-\d+(?:\.\d+)?)\.*$/g, "$1")
// return array
.split("."));
//sample
const type = {
"-1": "<",
"0": "=",
"1": ">"
},
classType = {
"-1": "old",
"0": "same",
"1": "new"
},
list = [
["1.0", "1.0.0.0.0.0"],
["1.0", "1.0.1"],
["1.0b1", "1.0"],
["1.0b", "1.0b"],
["1.1", "1.0.1b"],
["1.1alpha", "1.1beta"],
["1.1rc1", "1.1beta"],
["1.1rc1", "1.1rc2"],
["1.1.0a1", "1.1a2"],
["1.1.0a10", "1.1.0a1"],
["1.1.0alpha", "1.1a"],
["1.1.0alpha2", "1.1b1"],
["1.1.0--dev", "1.1_dev"],
["1.0001", "1.00000.1.0.0.0.01"]
],
inputA = document.getElementById("a"),
inputB = document.getElementById("b"),
result = document.getElementById("r"),
examples = document.getElementById("e"),
examplesRand = document.getElementById("er"),
str = ["", "a","b","alpha","beta","rc", "dev"];
function randVer(min, max)
{
if (typeof(min) == "undefined")
min = 4;
if (typeof(max) == "undefined")
max = 6;
const r = {a: "", b: ""};
for(let i = 2; i < rand(min, max); i++)
r.a += (r.a ? "." : "" ) + rand(0,9);
for(let i = 2; i < rand(min, max); i++)
r.b += (r.b ? "." : "" ) + rand(0,9);
if (rand(0,1))
{
if (rand(0,2))
r.b = r.a;
r.a += str[rand(0, str.length-1)] + (rand(0,1) ?...