JavaScript:完成与自己站点的相对URL
有没有更好的方法来编写这个过程来完成我的网站的相对urlJavaScript:完成与自己站点的相对URL,javascript,url,Javascript,Url,有没有更好的方法来编写这个过程来完成我的网站的相对url if (!url.startsWith('http')) { url = + location.protocol + '//' + location.host + (url.startsWith('/') ? '' : '/') + url }); 首先,可以有例如ftp:// 您应该检查url中是否有// 您应该使用“location”而不是“location.host”,并在最后一个“/”之后截断最后一个单词。我的意思是
if (!url.startsWith('http')) {
url = + location.protocol + '//' + location.host + (url.startsWith('/') ? '' : '/') + url
});
首先,可以有例如ftp:// 您应该检查url中是否有//
您应该使用“location”而不是“location.host”,并在最后一个“/”之后截断最后一个单词。我的意思是www. Pa.com/Fiel.HTML> www. pg. 你可能想考虑服务器端向你的网站提供基本URL。原因是,在服务器上访问站点的基本url通常比较容易。您所需要做的就是拥有一个服务器端脚本/操作,该脚本/操作生成一个如下所示的脚本:
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;
}
您可以在网页中将其称为:
<script type="text/javscript" src="/scripts/baseUrl.php"> // adjust for platform
</script>
我认为下面将正确处理所有可能的URL
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"))
lstrip=函数(str,前缀){
返回str.indexOf(前缀)==0?
str.substring(前缀.length):
str;
}
completeURL=函数(url,主机){
url=lstrip(url,“http:/”);
url=lstrip(url,主机);
url=lstrip(url,“/”);
返回“http://”+主机+“/”+url
}
//试验
URL=[
"http://host.com/foo/bar",
“host.com/foo/bar”,
“/foo/bar”,
“foo/bar”,
“foo.php”,
“host.com”,
""
]
对于(var n=0;n
这将为您提供绝对URL,而不是相对URL。JavaScript不会通过ftp://运行,因此您的第一场音乐会不应该成为问题。
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"))