Skip to content
Related Articles

Related Articles

Improve Article
How to check whether a given string is an absolute URL or not in JavaScript ?
  • Difficulty Level : Basic
  • Last Updated : 12 May, 2021

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 which 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.geeksforgeeks.org/

/* Relative Url */
geeksforgeeks.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 return false.



Approach: 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). 

Syntax:

^https:\/\/

Where,

  • ^: 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.

HTML




<!DOCTYPE html>
<html lang="en">
  
<body>
    <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>
    </form>
  
    <script>
        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";
            }
        }
    </script>
</body>
  
</html>

Output:

For non-absolute URL’s:

For absolute URL’s:




My Personal Notes arrow_drop_up
Recommended Articles
Page :