0

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:

  • 2.1.3
  • 3.3.4
  • 1140 or 2.0 (prefer)
  • 0.3.0
  • 2.1.0-X.10
  • 2.1.8-M1
  • null

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

1 Answer 1

0

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);
  });
Sign up to request clarification or add additional context in comments.

2 Comments

Is this from your github?
Yes, I found a few different regexes and combined them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.