How to useURL constructor in Javascript

Using URL constructor In this approach we will check if a given string is an absolute URL in JavaScript is by using the URL constructor and checking if it throws an error when trying to create a new URL instance from the string.

JavaScript
function isAbsoluteUrl(url) {
    try {
        new URL(url);
        return true;
    } catch (error) {
        return false;
    }
}

console.log(isAbsoluteUrl('https://www.example.com')); // Output: true
console.log(isAbsoluteUrl('www.example.com')); // Output: false
console.log(isAbsoluteUrl('/path/to/page')); // Output: false

Output
true
false
false

How to check whether a given string is an absolute URL or not in JavaScript ?

In this article, we will learn how to return true if the given string is an absolute URL in JavaScript. There are two types of URLs either relative or absolute.

Absolute URL: It is a URL that contains all the information that is important for locating the resources. The thing that is included in the absolute URL is the protocol (HTTPS) in the site’s domain at the starting point of the URL.

Relative URL: It is a short URL that holds the name of the domain and exact things which is only allowed to access on the same server or page. 

Syntax:

/* Absolute Url */
https://www.w3wiki.org/

/* Relative Url */
w3wiki.org

The task is to create a JavaScript function that takes an argument as a URL and returns true if the URL is an absolute link and if not then returns false.

Similar Reads

Approach 1: Using Regular Expression

Absolute URL has protocol (HTTPS) included in the starting. We can simply check if the URL has https:// in front or not. If it is found we return true else false....

Approach 2: Using URL constructor

Using URL constructor In this approach we will check if a given string is an absolute URL in JavaScript is by using the URL constructor and checking if it throws an error when trying to create a new URL instance from the string....