Recipe 3.1
Resolving a Relative URL
Enter a relative path and a base URL, and click “Get Full URL”. The absolute URL will be calculated and displayed.
Demo
Full URL
Code
JavaScript
function resolveUrl(relativePath, baseUrl) {
return new URL(relativePath, baseUrl).href;
}
const form = document.querySelector('#url-form');
form.addEventListener('submit', event => {
event.preventDefault();
const fullUrl = resolveUrl(
form.elements.relativePath.value,
form.elements.baseUrl.value
);
const result = document.querySelector('#result');
result.querySelector('#result-url').textContent = fullUrl;
result.classList.remove('d-none');
});
HTML
<div id="result" class="alert alert-primary d-none" role="alert">
<h4>Full URL</h4>
<code id="result-url"></code>
</div>
<form id="url-form">
<div class="mb-3">
<label for="relativePath" class="form-label">Relative Path</label>
<input required value="/api/users" type="text" id="relativePath" name="relativePath" class="form-control">
</div>
<div class="mb-3">
<label for="baseUrl" class="form-label">Base URL</label>
<input required type="url" value="https://example.com" id="baseUrl" name="baseUrl" class="form-control">
</div>
<button class="btn btn-primary">Get Full URL</button>
</form>