JavaScript check if an URL is http or https using check-more-types library
In this JavaScript tutorial we learn how to validate if a given string is an http or https using the http() and https() 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 HTTP URL in JavaScript
To check if a given URL is an HTTP URL or not we can use the http() method of check-more-types library. The method returns true if the provided URL starts with http://
In the sample-project directory create a new file named check-http.js as below.
check-http.js
var check = require('check-more-types');
console.log(check.http('http://toricode.com'));
console.log(check.http('https://toricode.com'));
Run the check-http.js file using the following command.
node check-http.js
true
false
How to check HTTPS URL in JavaScript
To check if a given URL is an HTTPS URL or not we can use the https() method of check-more-types library. The method returns true if the provided URL starts with https://
In the sample-project directory create a new file named check-https.js as below.
check-https.js
var check = require('check-more-types');
console.log(check.https('https://toricode.com'));
console.log(check.https('http://toricode.com'));
Run the check-https.js file using the following command.
node check-https.js
true
false
More examples of how to use the check.http() and check.https() method
check-http-example.js
var check = require('check-more-types');
var url = 'https://toricode.com';
if(check.http(url)) {
console.log(url + ' is an HTTP URL');
} else {
console.log(url + ' is not an HTTP URL');
}
if(check.https(url)) {
console.log(url + ' is an HTTPS URL');
} else {
console.log(url + ' is not an HTTPS URL');
}
Run the check-http-example.js file using the following command.
node check-http-example.js
https://toricode.com is not an HTTP URL
https://toricode.com is an HTTPS URL
Happy Coding 😊