JSFiddle - React, Tailwind, and code Playground
HTML
<input type="text" id="path" value="../b/c.txt" placeholder="path to resolve"/>
<input type="text" id="base" value="http://test.io/path/to/file.html" placeholder="base URL"/>
<pre id="result"></pre>
JavaScript
function resolveRelative(path, base) {
// Absolute URL
if (path.match(/^[a-z]*:\/\//)) {
return path;
}
// Protocol relative URL
if (path.startsWith("//")) {
return base.replace(/\/\/.*/, path)
}
// Upper directory
if (path.startsWith("../")) {
return resolveRelative(path.slice(3), base.replace(/\/[^\/]*$/, ''));
}
// Relative to the root
if (path.startsWith('/')) {
var match = base.match(/(\w*:\/\/)?[^\/]*\//) || [base];
return match[0] + path.slice(1);
}
//relative to the current directory
return base.replace(/\/[^\/]*$/, "") + '/' + path.replace(/^\.\//, '');
}
var path = document.getElementById("path");
var base = document.getElementById("base");
var result = document.getElementById("result");
function update () {
result.innerHTML = resolveRelative(path.value, base.value);
}
path.addEventListener("change", update);
path.addEventListener("keyup", update);
base.addEventListener("change", update);
base.addEventListener("keyup", update);
update();