从Javascript中的String获取版本号?

时间:2010-05-11 10:36:28

标签: javascript regex string

我有一个3位数字的版本号作为字符串,

var version = "1.2.3";

并希望将其与其他版本进行比较。要查看版本是否比其他版本更新,

var otherVersion = "1.2.4";

你会怎么做?

11 个答案:

答案 0 :(得分:8)

伪:

  • .
  • 上拆分
  • 按顺序比较部分:主要 - >次要 - > Rev(如果两个版本都存在部分)。
  • 如果oV [n]> v [n]:oV最大。
  • 另外:比较下一个子部分。

(请参阅@arhorns answer以获得优雅的实现)

答案 1 :(得分:6)

大多数提交版本的问题是它们无法处理任意数量的版本部分(例如1.4.2 .. 1.2等)和/或它们要求版本部分是单个数字,实际上并不常见。

改进了compareVersions()函数

如果v1大于v2,则此函数将返回1;如果v2大于此值,则返回-1 如果版本相同则为0(对于自定义排序也很方便)

我没有对输入进行任何错误检查。

function compareVersions (v1, v2)
{
    v1 = v1.split('.');
    v2 = v2.split('.');
    var longestLength = (v1.length > v2.length) ? v1.length : v2.length;
    for (var i = 0; i < longestLength; i++) {
        if (v1[i] != v2[i]) {
            return (v1 > v2) ? 1 : -1
        }
    }
    return 0; 
 }

答案 2 :(得分:4)

您可能希望使用以下实现(based on jensgram's solution):

function isNewer(a, b) {
   var partsA = a.split('.');
   var partsB = b.split('.');
   var numParts = partsA.length > partsB.length ? partsA.length : partsB.length;
   var i;

   for (i = 0; i < numParts; i++) {
      if ((parseInt(partsB[i], 10) || 0) !== (parseInt(partsA[i], 10) || 0)) {
         return ((parseInt(partsB[i], 10) || 0) > (parseInt(partsA[i], 10) || 0));
      }
   }

   return false;
}

console.log(isNewer('1.2.3', '1.2.4'));    // true
console.log(isNewer('1.2.3', '1.2.0'));    // false
console.log(isNewer('1.2.3', '1.2.3.1'));  // true
console.log(isNewer('1.2.3', '1.2.2.9'));  // false
console.log(isNewer('1.2.3', '1.2.10'));   // true

请注意,必须使用parseInt(),否则最后一次测试将返回false"10" > "3"返回false

答案 3 :(得分:3)

如果你的每个部分中只有一个数字,为​​什么不直接比较?

>>> var version = "1.2.3"; var otherVersion = "1.2.4"; version < otherVersion
true

它似乎也适用于缩写版本:

>>> '1.2' > '1.2.4'
false
>>> '1.3' > '1.2.4'
true

答案 4 :(得分:1)

function VersionValue(var str)
{
var tmp = str.split('.');
return (tmp[0] * 100) + (tmp[1] * 10) + tmp[2];
}

if (VersionValue(version) > VersionValue(otherVersion))...

例如

答案 5 :(得分:1)

由于我很无聊,这里的方法类似于我们的十进制系统(数十,数百,数千等),它使用正则表达式回调而不是循环:

function compareVersion(a, b) {
    var expr = /\d+/g, places = Math.max(a.split(expr).length, b.split(expr).length);
    function convert(s) {
        var place = Math.pow(100, places), total = 0;
        s.replace(expr,
            function (n) {
                total += n * place;
                place /= 100;
            }
        );
        return total;
    };

    if (convert(a) > convert(b)) {
        return a;
    }

    return b;
}

返回更高版本,例如:

compareVersion('1.4', '1.3.99.32.60.4'); // => 1.4

答案 6 :(得分:1)

function isCorrectVersion(used,required){
    var used = parseFloat("0."+used.replace(/\./gi,""));
    var required = parseFloat("0."+required.replace(/\./gi,""));

    return (used < required) ? false : true;
}

我用它来比较jQuery函数,它似乎工作正常,也比较例如1.4和1.4.1或1.4.1和1.4.11。

答案 7 :(得分:0)

使用其中一个比较运算符。

"1.2.3" > "1.2.4" //false

"1.2.3" < "1.2.4" //true

答案 8 :(得分:0)

也许这样(快速)?

function isNewer(s0, s1) {
    var v0 = s0.split('.'), v1 = s1.split('.');
    var len0 = v0.length, len1=v1.length;
    var temp0, temp1, idx = 0;
    while (idx<len0) {
        temp0 = parseInt(v0[idx], 10);
        if (len1>idx) {
            temp1 = parseInt(v1[idx], 10);
            if (temp1>temp0) {return true;}
        }
        idx += 1;
    }
    if (parseInt(v0[idx-1], 10)>parseInt(v1[idx-1], 10)) {return false;}
    return len1 > len0;
}
var version = "1.2.3";
var otherVersion = "1.2.4";

console.log('newer:'+(isNewer(version, otherVersion)));

它会处理不同数量的零件,但它只适用于点之间的数字。

答案 9 :(得分:0)

请注意,这些解决方案都不会故意为0.9beta1.0 RC 1之类的内容返回正确的结果。然而,它在PHP中非常直观地处理:http://de3.php.net/manual/en/function.version-compare.php并且有一个JS端口:http://phpjs.org/functions/version_compare(我不认为这是非常好或有效,只是'完整' )。

答案 10 :(得分:0)

我找不到一个返回1,0或-1的答案,同时处理尾随.0和两位数的部分,所以这里就是这样。这应该支持所有部分都是数字的所有情况(参见底部的测试)。

/*
 * Returns 1 if v1 is newer, -1 if v2 is newer and 0 if they are equal.
 * .0s at the end of the version will be ignored.
 *
 * If a version evaluates to false it will be treated as 0.
 *
 * Examples:
 * compareVersions ("2.0", "2") outputs 0,
 * compareVersions ("2.0.1", "2") outputs 1,
 * compareVersions ("0.2", "0.12.1") outputs -1,
 *
 */
function compareVersions (version1, version2) {
  var version1 = version1 ? version1.split('.') : ['0'],
      version2 = version2 ? version2.split('.') : ['0'],
      longest = Math.max(version1.length, version2.length);

  for (var i = 0; i < longest; i++) {
    /*
     * Convert to ints so that we can compare two digit parts
     * properly. (Otherwise would "2" be greater than "12").
     *
     * This returns NaN if the value is undefined, so we check for
     * NaN later.
     */
    var v1Part = parseInt(version1[i]),
        v2Part = parseInt(version2[i]);

    if (v1Part != v2Part) {

      // version2 is longer
      if (isNaN(v1Part)) {
        /*
         * Go through the rest of the parts of version 2. If it is only zeros,
         * consider the versions equal, otherwise consider version 2 as newer.
         */
        for (var j = i; j < longest; j++) {
          if (parseInt(version2[j]) != 0) return -1;
        }

      // version1 is longer
      } else if (isNaN(v2Part)) {
        for (var j = i; j < longest; j++) {
          if (parseInt(version1[j]) != 0) return 1;
        }

      // versions are equally long
      } else {
        return (v1Part > v2Part) ? 1 : -1;
      }
      return 0;
    }
  }
  return 0;
}

console.log(compareVersions("1", "1") === 0);
console.log(compareVersions("1.1", "1") === 1);
console.log(compareVersions("1.1.1", "1") === 1);
console.log(compareVersions("1", "1.1.1") === -1);
console.log(compareVersions("0.3", "0.3.0.0.1") === -1);
console.log(compareVersions("0.3", "0.3.0") === 0);
console.log(compareVersions("0.3.0.0.1", "0.3") === 1);
console.log(compareVersions("0.3.0", "0.3") === 0);
console.log(compareVersions("0.12", "0.2") === 1);
console.log(compareVersions("0.2", "0.12") === -1);
console.log(compareVersions("0.12.0", "0.2") === 1);
console.log(compareVersions("0.02.0", "0.2") === 0);
console.log(compareVersions("0.01.0", "0.2") === -1);