JavaScript Check whether a URL string is absolute or relative
Last Updated :
18 Jul, 2023
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:
Use Regular Expression which checks if the URL contains “//” at a position in the URL.
Example: This example uses the approach discussed above.
Javascript
console.log(URL);
function gfg_Run() {
let RgExp = new RegExp( "^(?:[a-z]+:)?//" , "i" );
if (RgExp.test(URL)) {
console.log( "This is Absolute URL." );
} else {
console.log( "This is Relative URL." );
}
}
gfg_Run();
|
Output
https://geeksforgeeks.org
This is Absolute URL.
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
let URL = "/myfolder/test.txt" ;
console.log(URL);
function gfg_Run() {
if (URL.indexOf( "://" ) > 0 || URL.indexOf( "//" ) === 0) {
console.log( "This is Absolute URL." );
} else {
console.log( "This is Relative URL." );
}
}
gfg_Run();
|
Output
/myfolder/test.txt
This is Relative URL.
Share your thoughts in the comments
Please Login to comment...