DEV Community

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

Posted on

4

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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay