ES5 - 从src路径解析脚本版本

时间:2015-04-21 02:58:06

标签: javascript semantic-versioning

我希望有人已经完成了这项工作,但我正在尝试做的是输出各种javascript库的语义版本列表。我们假设我有以下输入:

我想在每个字符串上调用一个函数,让它从路径输出semver:

  • 2.1.3
  • 3.3.4
  • 1140或2.0(首选)
  • 0.3.0
  • 2.1.0-X.10
  • 2.1.8-M1

我无法找到任何现有的图书馆,并且希望有人能够使用IE9ish。

1 个答案:

答案 0 :(得分:0)

我可以使用following code

来解决这个问题
  it('should parse version from script source', () => {
    function getVersion(source:string) {
      if (!source) {
        return null;
      }

      var versionRegex = /(v?((\d+)\.(\d+)(\.(\d+))?)(?:-([\dA-Za-z\-]+(?:\.[\dA-Za-z\-]+)*))?(?:\+([\dA-Za-z\-]+(?:\.[\dA-Za-z\-]+)*))?)/;
      var matches = versionRegex.exec(source);
      if (matches && matches.length > 0) {
        return matches[0];
      }

      return null;
    }

    expect(getVersion('https://code.jquery.com/jquery-2.1.3.js')).toBe('2.1.3');
    expect(getVersion('//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css')).toBe('3.3.4');
    expect(getVersion('https://cdnjs.cloudflare.com/ajax/libs/1140/2.0/1140.css')).toBe('2.0');
    expect(getVersion('https://cdnjs.cloudflare.com/ajax/libs/Base64/0.3.0/base64.min.js')).toBe('0.3.0');
    expect(getVersion('https://cdnjs.cloudflare.com/ajax/libs/angular-google-maps/2.1.0-X.10/angular-google-maps.min.js')).toBe('2.1.0-X.10');
    expect(getVersion('https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/2.1.8-M1/swagger-ui.min.js')).toBe('2.1.8-M1');
    expect(getVersion('https://cdnjs.cloudflare.com/BLAH/BLAH.min.js')).toBe(null);
  });