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:
- using JavaScript Regular Expression
- using JavaScript string.indexof() method
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.