Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to test if a URL string is absolute or relative - JavaScript?
Knowing whether a URL string is absolute or relative allows you to make decisions about content loading and routing in your JavaScript applications. In this article, we'll explore different methods to determine if a given URL string is absolute or relative.
Understanding URL Types
Absolute URL contains all necessary information to locate a resource, including the protocol (http/https) and domain name.
Syntax
https://www.tutorialspoint.com/index.htm
Relative URL contains only the path information and relies on the current page's context to resolve the full location.
Syntax
/index.htm ../images/logo.png index.htm
Method 1: Using Regular Expression
Regular expressions can check if a URL starts with a protocol. This method looks for patterns like http:// or https:// at the beginning of the string.
Example
<!DOCTYPE html>
<html>
<body>
<form>
<label for="url">Enter URL:</label>
<input type="text" id="url" placeholder="Enter URL here">
<button type="button" onclick="checkURL()">Check URL</button>
<h3 id="result"></h3>
</form>
<script>
function checkURL() {
let url = document.getElementById('url').value;
let result = document.getElementById('result');
// Pattern to match http:// or https:// at the start
let pattern = /^https?:\/\//i;
if (pattern.test(url)) {
result.innerText = "Absolute URL";
result.style.color = "green";
} else {
result.innerText = "Relative URL";
result.style.color = "blue";
}
}
</script>
</body>
</html>
Testing Multiple URLs with Regex
<!DOCTYPE html>
<html>
<body>
<script>
function isAbsoluteURL(url) {
let pattern = /^https?:\/\//i;
return pattern.test(url);
}
let urls = [
"https://www.tutorialspoint.com/index.htm",
"/tutorials/javascript/",
"http://example.com",
"../images/logo.png",
"index.html"
];
urls.forEach(url => {
let type = isAbsoluteURL(url) ? "Absolute" : "Relative";
document.write(url + " ? " + type + "<br>");
});
</script>
</body>
</html>
Method 2: Using indexOf() Method
The indexOf() method searches for the protocol separator :// in the URL string. If found at position greater than 0, or if the URL starts with //, it's considered absolute.
Example
<!DOCTYPE html>
<html>
<body>
<div style="text-align:center;">
<p id="demo" style="font-size: 18px; font-weight: bold;"></p>
<button onclick="checkURLType()">Check URL Type</button>
<p id="result" style="color:green; font-size: 20px; font-weight: bold;"></p>
</div>
<script>
function checkURLType() {
let urls = [
"https://www.tutorialspoint.com/index.htm",
"/javascript/tutorial.htm",
"//cdn.example.com/script.js"
];
let resultElement = document.getElementById("result");
let output = "";
urls.forEach(url => {
let isAbsolute = url.indexOf('://') > 0 || url.indexOf('//') === 0;
let type = isAbsolute ? "Absolute" : "Relative";
output += url + " ? " + type + "<br>";
});
resultElement.innerHTML = output;
document.getElementById("demo").innerHTML = "URL Analysis Results:";
}
</script>
</body>
</html>
Method 3: Using URL Constructor (Modern Approach)
The most robust method uses the native URL constructor, which can properly parse and validate URLs.
<!DOCTYPE html>
<html>
<body>
<script>
function isAbsoluteURL(url) {
try {
new URL(url);
return true; // Valid absolute URL
} catch {
return false; // Invalid or relative URL
}
}
let testUrls = [
"https://www.tutorialspoint.com",
"http://example.com/path",
"/relative/path",
"relative.html",
"../parent/file.html",
"mailto:test@example.com",
"ftp://files.example.com"
];
document.write("<h3>URL Type Detection:</h3>");
testUrls.forEach(url => {
let type = isAbsoluteURL(url) ? "Absolute" : "Relative";
document.write("<strong>" + url + "</strong> ? " + type + "<br>");
});
</script>
</body>
</html>
Comparison of Methods
| Method | Accuracy | Browser Support | Handles Edge Cases |
|---|---|---|---|
| Regular Expression | Good | All browsers | Limited |
| indexOf() | Good | All browsers | Basic |
| URL Constructor | Excellent | Modern browsers | Comprehensive |
Conclusion
Use the URL constructor for modern applications as it provides the most accurate results. For broader browser support, regular expressions or indexOf() methods work well for basic URL validation.
