Javascript: Check if string is url

This article discusses checking if a string is a valid URL in javascript using different methods and examples for illustration.

Table of Contents:

Javascript check if string is URL: regex

This section will look into the javascript function, which checks if the string is a valid URL. The function checks for a pattern in the string, and if the pattern matches, then returns true. Else returns false. Observe the below pattern.

Javascript function to check if the string is a valid URL

The pattern in this function will check for a valid URL skeleton such as the URL protocol, domain name, ip address etc.

function isValidUrl(_string) {
  const matchpattern = /^https?:\/\/(?:www\.)?[[email protected]:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm;
  return matchpattern.test(_string);
}

OR

function isValidUrl(_string){
  const matchPattern = /^(?:\w+:)?\/\/([^\s\.]+\.\S{2}|localhost[\:?\d]*)\S*$/;
  return matchPattern.test(_string);
}

Test with Example_1:

Check if the string “A Random String” is a valid URL.

let _string1 = "A Random String"
isValidUrl(_string1) ? console.log("URL is Valid") : console.log("URL is Invalid")

Output:-

URL is Invalid

Test with Example_2:

Check if string “https://www.managementbliss.com” is a valid URL

let _string1 = "https://www.managementbliss.com"
isValidUrl(_string1) ? console.log("URL is Valid") : console.log("URL is Invalid")

Output:-

URL is Valid

Javascript check if string is URL using URL Interface

In this section, we will use the URL Interface to check if the string is a valid URL or not.

Javascript function to check if the string is a valid URL

The below function checks if the string is a valid URL. A URL constructor is used to create a new URL object and then check if the url_object.protocol equals http or https. The function returns true if the url_object.protocol is either https or http. Else returns false.

function isValidUrl(_string) {
  let url_string; 
  try {
    url_string = new URL(_string);
  } catch (_) {
    return false;  
  }
  return url_string.protocol === "http:" || url_string.protocol === "https:" ;
}

Test with Example_1:

Check if the string “A Random String” is a valid URL.

let _string1 = "A Random String"
isValidUrl(_string1) ? console.log("URL is Valid") : console.log("URL is Invalid")

Output:-

URL is Invalid

Test with Example_2:

Check if the string “https://www.managementbliss.com” is a valid URL.

let _string1 = "https://www.managementbliss.com"
isValidUrl(_string1) ? console.log("URL is Valid") : console.log("URL is Invalid")

Output:-

URL is Valid

Read More:

We hope this article helped you to check if the javascript string is a valid URL. Good Luck !!!

Advertisements

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top