← Back to all snippets
JAVASCRIPT

Parse Semantic Version Strings

Use regex in JavaScript to accurately parse semantic version strings (e.g., '1.2.3-beta.4'), extracting major, minor, patch, and pre-release components.

function parseSemanticVersion(versionString) {
    const semVerRegex = new RegExp(
        /^v?(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-]+)*))?$/
    );
    const match = versionString.match(semVerRegex);

    if (!match) {
        return null;
    }

    return {
        full: match[0],
        major: parseInt(match[1], 10),
        minor: parseInt(match[2], 10),
        patch: parseInt(match[3], 10),
        prerelease: match[4] || null,
        build: match[5] || null
    };
}

// Examples:
// console.log(parseSemanticVersion("1.0.0"));
// console.log(parseSemanticVersion("v2.1.5-beta.3+build.123"));
// console.log(parseSemanticVersion("0.5.0-alpha"));
// console.log(parseSemanticVersion("invalid-version")); // null
How it works: The `parseSemanticVersion` function takes a version string and uses a regular expression compliant with SemVer 2.0.0 specifications to break it down. It captures the major, minor, and patch numbers, and optionally extracts pre-release identifiers and build metadata into a structured object, returning `null` if the string doesn't conform.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs