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

enlightened 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.

read more on 
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf 
OR https://www.w3schools.com/jsref/jsref_indexof.asp#:~:text=The%20indexOf()%20method%20returns,()%20method%20is%20case%20sensitive.

0 Comments

Leave a reply

Your email address will not be published. required fields are marked *