2017-07-06 33 views
3

我得到太多的方法可以得到像下面的代码的主机的主机名(基本URL):得到使用JavaScript

window.location.host // you'll get sub.domain.com:8080 or sub.domain.com:80 
window.location.hostname // you'll get sub.domain.com 
window.location.protocol // you'll get http: 
window.location.port // you'll get 8080 or 80 
window.location.pathname // you'll get /virtualPath 

在我来说,我想要的东西不同。例如:

我的QA网站的名称是example.com/testsite/index.html

我PROD网站的名称是example.com/index.html

这里的问题使用上述方法来获得它返回我只喜欢这个主机的主机名:example.com

然而,对于QA我需要返回example.com/testsite

对于PROD我需要返回example.com

单个代码可能吗?提前致谢。

+0

最好的方法,你已经拥有的INF ormation你需要...'window.location.hostname + window.location.pathname'我不明白是什么问题:/ – vsync

+0

感谢您的评论, 但我不知道我是否在质量保证或产品代码侧。来制作实际的路径 –

+0

你的问题的标题并不代表你正面临的问题 – vsync

回答

3

要达到您的要求,您需要检查window.location.hostname以及window.location.pathname中的第一个文件夹。类似这样的:

function getPath() { 
    var folder = (window.location.pathname.split('/')[0] || '').toLowerCase() == 'testsite' ? '/testsite' : ''; 
    return window.location.hostname + folder; 
} 
+0

感谢@Rory的回复,但没有像我的网站下的文件夹“testsite”的修复名称 –

+0

你的问题说有.. 。? –

+0

好的,但只要将字符串更改为任何它应该。逻辑是相同的 –

0

使用window.location.hostname;

例子:
网址为http://localhost:2239/Default2.aspx?id=5&name=SatinderSingh

var getCurrentURL =window.location.href; //http://localhost:2239/Default2.aspx?id=5&name=SatinderSingh 
var getHostname=window.location.hostname; //localhost 
var getPathName=window.location.pathname // Default2.aspx 
var getPortNo=window.location.port  // 2239 
var getQueryString=window.location.search //?id=5&name=SatinderSingh 

var getHostname = window.location.hostname; //localhost 
    var getPathName = window.location.pathname // Default2.aspx 
    var split_PathName = String(getPathName.split("/"));   
    var FinalURL = getHostname + "/" + split_PathName[1] 
+0

但是在响应中获取'/ testsite'路径呢? –

+0

感谢@Satinder对你的回应,但是如果对于QA'(localhost/testsite/test/form.html)',在这种情况下它会起作用。但PROD'(localhost/test/form.html)'它会给错误的finalurl –

1

,对于这两种PROD工作& QA

var BASE_URL = window.location.href; 
    BASE_URL = BASE_URL.split("testsite"); 
    if (BASE_URL.length > 1) 
    { 
     BASE_URL = BASE_URL[0]; 
     BASE_URL = BASE_URL + 'testsite'; 
    } else{ 
     BASE_URL = window.location.origin; 
    }