Javascript url resolver
Use this to resolve any url against any other base_url.
HTML
<label>page url: <input type="url" id="page" disabled></label>
resolve( "<label><input type="url" id="url" value="?foo=bar">" // url</label>
, "<label><input type="url" id="base" value="https://google.com/search">" // base url</label>
)
absolute: "<label><input type="url" id="resolved" disabled></label>" // resolved
CSS
input { width: 50%; }
body { font-family: monospace; white-space: pre; }
JavaScript
function resolve(url, base_url) {
var doc = document
, old_base = doc.getElementsByTagName('base')[0]
, old_href = old_base && old_base.href
, doc_head = doc.head || doc.getElementsByTagName('head')[0]
, our_base = old_base || doc_head.appendChild(doc.createElement('base'))
, resolver = doc.createElement('a')
, resolved_url
;
our_base.href = base_url || '';
resolver.href = url;
resolved_url = resolver.href; // browser magic at work here
if (old_base) old_base.href = old_href;
else doc_head.removeChild(our_base);
return resolved_url;
}
function getBaseURL () {
// return location.protocol + "//" + location.hostname +
// (location.port && ":" + location.port) + "/";
alert(location.protocol + "//" + location.hostname +
(location.port && ":" + location.port) + "/");
}
getBaseURL();
$('#page').val(location.href);
$('#url,#base').on('keyup', show).trigger('keyup');
function show() {
$('#resolved').val(resolve($('#url').val(), $('#base').val()));
}