Open In App

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

Last Updated : 15 Mar, 2024
Like Article

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. 


/* Absolute Url */

/* Relative Url */

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.

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. 

For checking protocol, we use regex (regular expression). 




  • ^: It is used for selecting from starting.
  • https: It is used for selecting the text.
  • \: It is used for a special regex character matches the front character.

Example: Below example explains the use of above approach.

    <h1 style="color: green;">GeeksforGeeks</h1>
    <form action="#">
        <label for="#">Please input the url</label>
        <input type="text" id="url">
        <input type="button" onclick="absolute_url()" value="Click">
        <h2 id="result"></h2>
        function absolute_url() {
            let urls = document.getElementById('url').value;
            let result = document.getElementById('result');
            // Regex pattern for checking
            var pattern = /^https:\/\//i;
            // Check if pattern is there in the string 
            // or not with .test() method
            if (pattern.test(urls)) {
                result.innerText = "true";
            else {
                result.innerText = "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.

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

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads