Yogesh Chauhan's Blog

How to check if a link has http or https in it in JavaScript?

in JavaScript on June 19, 2020

We can use RegEx (Regular Expressions) to check if http or https exists in the URL string. But there is another quick way as well.

We can use indexOf() to to check for the same.

Example


function validateURL(link)
{
    if (link.indexOf("http://") == 0 || link.indexOf("https://") == 0) {
        console.log("The link has http or https.");
    }
    else{
        console.log("The link doesn't have http or https.");      
    }
}

validateURL("www.yogeshchauhan.com/");

// The link doesn't have http or https.

Same example with https


function validateURL(link)
{
    if (link.indexOf("http://") == 0 || link.indexOf("https://") == 0) {
        console.log("The link has http or https.");
    }
    else{
        console.log("The link doesn't have http or https.");      
    }
}

validateURL("https://www.yogeshchauhan.com/");

// The link has http or https.

Discussion

JavaScript String indexOf() Method

👉 The indexOf() method returns the position of the first occurrence of a specified value in a string.

It returns -1 if the value doesn't exist in the string.

Also, it is case sensitive.

The method is supported by all major browsers.

You can also specify the search position, meaning the search will start from that position in the string.

Credit: MDN Docs


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to Use Aggregate Functions (MIN, MAX, SUM, AVG, COUNT) to Summarize Data in SQL?SQL/MySQLHow to remove special characters (dash, asterisk etc) from any string in PHP?PHPCurrencyPipe in Angular 9 with ExamplesAngularDid you get an error while displaying Special Characters in JavaScript?JavaScriptHow services and dependency injection work in Angular?AngularHow to avoid element shift on border change while hovering in CSS?CSS