Is there a better way to write this procedure that completes a relative url for my website?
if (!url.startsWith('http')) {
url = + location.protocol + '//' + location.host + (url.startsWith('/') ? '' : '/') + url
});
Is there a better way to write this procedure that completes a relative url for my website?
if (!url.startsWith('http')) {
url = + location.protocol + '//' + location.host + (url.startsWith('/') ? '' : '/') + url
});
On first there can be for example ftp://
You should check if there is any // in url.
And instead of 'location.host' you should use 'location' with cut off the last word after the last: "/". I mean www.page.com/file.html -> www.page.com
You might want to consider having the server side supply the base url to your web site. The reason being, that it is typically easier to get access to the base url of the site on the server. All you need to do is have a server-side script/action that generates a script that looks like:
var siteBaseUrl = 'http://example.com/';
// use string replacement to remove any leading slash on the incoming url.
function makeAbsoluteUrl( url )
{
if (!url.match(/^http/)) {
url = siteBaseUrl + url.replace(/^\//,'');
})
return url;
}
You can refer to it in your web page as:
<script type="text/javscript" src="/scripts/baseUrl.php"> // adjust for platform
</script>
And use it as
url = makeAbsoluteUrl( url );
i think the following would handle all possible urls correctly
lstrip = function(str, prefix) {
return str.indexOf(prefix) == 0 ?
str.substring(prefix.length) :
str;
}
completeURL = function(url, host) {
url = lstrip(url, "http://");
url = lstrip(url, host);
url = lstrip(url, "/");
return "http://" + host + "/" + url
}
//test
urls = [
"http://host.com/foo/bar",
"host.com/foo/bar",
"/foo/bar",
"foo/bar",
"foo.php",
"host.com",
""
]
for(var n = 0; n < urls.length; n++)
console.log(completeURL(urls[n], "host.com"))