The Wayback Machine - https://web.archive.org/web/20240407020454/https://www.geeksforgeeks.org/javascript-check-whether-a-url-string-is-absolute-or-relative/
Open In App

JavaScript Check whether a URL string is absolute or relative

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, the task is to check if the passed URL is absolute or relative. Below are a few approaches: 

Approaches to Check if URL is Absolute or Relative:

Approach 1: Using JavaScript Regular Expression

Use Regular Expression which checks if the URL contains “//” at a position in the URL.

Example: This example uses the approach discussed above.

Javascript




// Input url
 
// Display input url
console.log(URL);
 
// Function to check url
function gfg_Run() {
    // Regular Expression to check url
    let RgExp = new RegExp("^(?:[a-z]+:)?//", "i");
    if (RgExp.test(URL)) {
        console.log("This is Absolute URL.");
    } else {
        console.log("This is Relative URL.");
    }
}
 
// Function call
gfg_Run();


Output

https://geeksforgeeks.org
This is Absolute URL.

Approach 2: Using JavaScript string.indexof() method

Use .indexOf() method to get to know if the position of “://” has an index greater than 0 or if the position of “//” has an index equal to 0. Both these conditions check to lead us to the absolute URL.

Example: This example uses the approach discussed above.

Javascript




// Input url
let URL = "/myfolder/test.txt";
 
// Display input url
console.log(URL);
 
// Function to check url type
function gfg_Run() {
    // Using index of to check url format
    if (URL.indexOf("://") > 0 || URL.indexOf("//") === 0) {
        console.log("This is Absolute URL.");
    } else {
        console.log("This is Relative URL.");
    }
}
 
// Function call
gfg_Run();


Output

/myfolder/test.txt
This is Relative URL.



Last Updated : 18 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments

Similar Reads