Blake Niemyjski
Blake Niemyjski

Reputation: 3577

ES5 - Parse script version from src path

I was hoping someone already had this done but what I'm trying to do is output a list of semantic versions of various javascript libraries. Let's assume I have the the following input:

I'd like to call a function on each of these strings and have it output the semver from the path:

I was unable to find any existing libraries and was hoping someone had one handy that worked on IE9ish.

Upvotes: 0

Views: 110

Answers (1)

Blake Niemyjski
Blake Niemyjski

Reputation: 3577

I was able to get this to work by using the 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);
  });

Upvotes: 0

Related Questions