How to test if a URL string is absolute or relative - JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

To test for a URL string, use regular expression.

Example

Following is the code −

var regularExpressionForURL = /^https?:\/\//i;
var originalURL1 = "https://www.example.com/index";
var originalURL2 = "/index";
if (regularExpressionForURL.test(originalURL1)) {
   console.log("This is absolute URL");
}
else {
   console.log("This is relative URL");
}
if (regularExpressionForURL.test(originalURL2)) {
   console.log("This is absolute URL");
}
else {
   console.log("This is relative URL");
}

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo266.js

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo266.js
This is absolute URL
This is relative URL
raja
Published on 09-Nov-2020 07:45:17
Advertisements