使用javascript获取主机名(基本URL)

时间:2017-07-06 09:36:09

标签: javascript jquery

我有太多方法可以获得如下代码的主机名:

   assertNoNull(obj.getId());
   assertTrue(obj.getId().longValue()>0);

在我的情况下,我想要一些不同的东西。例如:

我的质量保证网站名称为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

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

这里使用上述方法获取主机名的问题只返回主机名,如下所示:example.com/index.html

但是对于QA,我需要返回example.com

对于PROD,我需要返回example.com/testsite

单一代码可以吗?提前谢谢。

3 个答案:

答案 0 :(得分:3)

要实现您的要求,您需要查看window.location.hostname以及window.location.pathname中的第一个文件夹。像这样:

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

答案 1 :(得分:1)

适用于PROD和EXD的最佳方法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;
   }

答案 2 :(得分: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]