JavaScript check if a string is exact semver format using check-more-types library

In this JavaScript tutorial we learn how to check a given string to determine if it is an exact semver format or not using the semver() method of check-more-types module.

Create the sample project

Firstly we create an empty project with the following command.

mkdir sample-project
cd sample-project
npm init -y

And install the check-more-types module using the following command.

npm install check-more-types --save

How to check if a string is exact semver in JavaScrip

To check if a given string is an exact semver format or not we can use the semver() method of check-more-types library. The method returns true if the given string is in semver format.

In the sample-project directory create a new file named check-semver.js as below.

check-semver.js

var check = require('check-more-types');

console.log(check.semver('1.2.3'));
console.log(check.semver('1.2.3-test'));

Run the check-semver.js file using the following command.

node check-semver.js
The output is:
true
false

More examples of how to use the check.semver() method

check-semver-example.js

var check = require('check-more-types');

var version1 = '1.0.3';
var version2 = '1.0.2-version';

if(check.semver(version1)) {
    console.log(version1 + ' is exactly semver.')
} else {
    console.log(version1 + ' is not a semver.')
}

if(check.semver(version2)) {
    console.log(version2 + ' is exactly semver.')
} else {
    console.log(version2 + ' is not a semver.')
}

Run the check-semver-example.js file using the following command.

node check-semver-example.js
The output is:
1.0.3 is exactly semver.
1.0.2-version is not a semver.

Happy Coding 😊