JavaScript check if a string is a valid web URL using check-more-types library

In this JavaScript tutorial we learn how to check whether a given string is a valid web URL or not using the webUrl() method of the check-more-types library.

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 valid web URL in JavaScript

To check if a given string is a valid web URL or not we can use the webUrl() method of check-more-types library. The method return true if the given string starts with http:// or https://

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

check-web-url.js

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

console.log(check.webUrl('https://toricode.com'));
console.log(check.webUrl('http://toricode.com'));
console.log(check.webUrl('tori code'));

Run the check-web-url.js file using the following command.

node check-web-url.js
The output is:
true
true
false

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

check-web-url-example.js

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

var string1 = 'https://toricode.com';
var string2 = 'tori code';

if(check.webUrl(string1)) {
    console.log(string1 + ' is a valid web URL.');
} else {
    console.log(string1 + ' is not a valid web URL.');
}

if(check.webUrl(string2)) {
    console.log(string2 + ' is a valid web URL.');
} else {
    console.log(string2 + ' is not a valid web URL.');
}

Run the check-web-url-example.js file using the following command.

node check-web-url-example.js
The output is:
https://toricode.com is a valid web URL.
tori code is not a valid web URL.

Happy Coding 😊