DEV Community

Cover image for Parsing SemVer in Javascript with the official RegEx
Andreas Riedmüller
Andreas Riedmüller

Posted on

Parsing SemVer in Javascript with the official RegEx

Recently I had to parse a SemVer string. The first Regex I found was not able to deal with labels, so I went to the SemVer docs to learn more about the exact specs for the label.

And I found that the official Semantic Versioning 2.0.0 documentation (the english version at least) includes a official regex with numbered capture groups that is compatible with ECMA Script (JavaScript), PCRE (Perl Compatible Regular Expressions, i.e. Perl, PHP and R), Python and Go.

And it even has tests, very handy!

You can use it to verify/validate and parse your SemVer string at the same time:

const versionString = "1.2.3-rc.1";
const [semVer, major, minor, patch, prerelease, buildmetadata] = versionString.match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/) ?? []; 
Enter fullscreen mode Exit fullscreen mode

💡 The variable names should be self explanatory. If semverString is not a valid SemVer, .match() will return null and all values will be undefined.

Do you have another method for testing/parsing SemVer? If yes, how and why?

Hope it helps someone, have a great day!

Top comments (0)