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 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
The Lending Club Analysis using Logistic Regression and Random Forest in RStudioMiscellaneousHow to zoom an element on hover using CSS?CSSFlash of Invisible Text and Mitt Romney Web Font ProblemCSSHow to embed YouTube or other video links in WordPress?WordPressThe difference between isFinite() method and isFinite() function in JavaScriptJavaScriptPHP arrays for US states’ full names and abbreviationsPHP