2013-01-13 15 views
0

有很多帖子都在寻找解析url并获取主机名的方法。正常的解决方案是创建一个文档元素,设置一个url,并访问.hostname属性。这是一个很好的解决方案。除了这种技术之外,我遇到了麻烦。用javascript进一步解析url主机名

我有一个从主机名中成功提取基本主机的函数。为了描述基本主机的含义(不确定正确的命名法),我将显示该功能并给出一些示例输入输出。

function parseURL(url) { 
    var parser = document.createElement('a'); 
    parser.href = url; 
    url = parser.hostname; 
    //get a version of the url with the last "." and everything beyond it truncated. 
    //Uses this as a trick in the next step to get the "second to last" index. 
    url = url.substr(0, url.lastIndexOf(".")); 
    //get a version of the url with everything before the second to last "." truncated. 
    url = parser.hostname.substr(url.lastIndexOf(".")+1); 
    return url; 
}; 
parseURL("http://code.google.com/p/jsuri/") 
//google.com - I don't think jsuri handle hosts any more effectively 
parseURL("http://www.nytimes.com/pages/nyregion/index.html") 
//nytimes.com 
parseURL("http://fivethirtyeight.blogs.nytimes.com/2013/01/12/in-cooperstown-a-crowded-waiting-room/" 
//nytimes.com 
parseURL("http://www.guardian.co.uk/uk/2013/jan/13/fears-lulworth-cove-development-heritage" 
//co.uk 

最后一个例子是我害怕的例外,为什么我要寻找更可行的解决方案。用于获取主机的.hostname方法是一个很好的第一步,我正在寻找一种更好的方法来破解有时位于基本级主机之前的子主机。

任何帮助赞赏(如果只是纠正我的术语)。

回答

0

你应该能够基于这样的事实,像在您的示例.uk国家代码顶级域总是2个字符(声明为清楚起见变量)的代码分支:

// Grab the last bit (the top level domain) 
var tld = url.subtr(url.lastIndexOf(".")) 
if (tld.length === 2) 
    //do stuff 
else if (tld.length === 3) 
    //do other stuff 

此外,我相信你正在寻找的字因为是“域名”,尽管通过一些计算包括“子域名”(位于docs.google.com谷歌之前的位)。

+0

是的,我认为字符串的长度是做这项工作的关键。谢谢您的帮助。 –

0

当我想要解析的网址,我做这样的事情

function parseURL(url) { 
    var a = document.createElement('a'), obj, i, j; 
    a.href = url; 
    obj = { 
     'domain': '', 
     'hash': a.hash.slice(1), 
     'host': a.host, 
     'hostname': a.hostname, 
     'href': a.href, // copy back from <a> 
     'origin': a.origin, 
     'pathname': a.pathname, 
     'port': a.port, 
     'protocol': a.protocol.slice(0, -1), 
     'search': a.search.slice(1), 
     'subdomain': '' 
    }; 
    i = obj.hostname.lastIndexOf('.'); 
    if (obj.hostname.length - i === 3) { // if .yz 
     j = obj.hostname.lastIndexOf('.', i-1); 
     if (j === i - 3 || j === i - 4) { // test .vwx.yz or .wx.yz 
      i = j; 
     } 
    } 
    j = obj.hostname.lastIndexOf('.', i-1); 
    if (j !== -1) { // move back one more . 
     i = j; 
    } 
    obj.domain = obj.hostname.slice(i+1); 
    obj.subdomain = obj.hostname.slice(0, i); 
    return obj; 
}; 

现在,如果你使用它,

var myURL = parseURL('http://www.example.co.uk:8080/hello/world.html?foo=bar#anchor'); 
/* { 
    "domain": "example.co.uk", 
    "hash": "anchor", 
    "host": "www.example.co.uk:8080", 
    "hostname": "www.example.co.uk", 
    "href": "http://www.example.co.uk:8080/hello/world.html?foo=bar#anchor", 
    "origin": "http://www.example.co.uk:8080", 
    "pathname": "/hello/world.html", 
    "port": "8080", 
    "protocol": "http", 
    "search": "foo=bar", 
    "subdomain": "www" 
} */ 

所以你想要的东西,你会用myURL.domain(或删除其余来自功能)

+0

Paul,这是我期待做的一个非常好的实现,我非常感谢你发布它。一个反馈 - 这里的局限性是次要域(或者叫做什么)必须是2或3个字符。其中有一些更多。在英国,例如judiciary.uk和parliament.uk。 wiki.br是一个巴西的wiki前缀。 仍然要通过您的代码工作,看看我是否可以建议更新。不过,这是对我丑陋代码的巨大升级。谢谢。 –

+0

我拥有它的方式意味着您不需要使用字典进行比较。对于你所要求的,你需要某种对象来使用字典,例如'dict = {'uk':{'judiciary':1,'parliament':1},'br':{'wiki':1}}'然后'if('br'in dict &&'wiki'in dict ['br'])/ *做一些特别的事情* /;' –

+0

有道理。谢谢。我甚至不确定我是否还需要这样的成熟度。感谢你的帮助。 –

0
function parseURL(str) { 
    var re = /^(?:([a-zA-Z]+:)\/\/)?(?:([-+._a-zA-Z0-9]+)(?::([-+._a-zA-Z0-9]+))[email protected])?(([^[email protected]#$%^^&*\(\)_+=\[\]{}:;'"\\,.\/?\s]+(?:[^[email protected]#$%^^&*\(\)_+=\[\]{}:;'"\\,.\/?\s]+[^[email protected]#$%^^&*\(\)_+=\[\]{}:;'"\\,.\/?\s])*(?:\.[^[email protected]#$%^^&*\(\)_+=\[\]{}:;'"\\,.\/?\s]+(?:[^[email protected]#$%^^&*\(\)_+=\[\]{}:;'"\\,.\/?\s]+[^[email protected]#$%^^&*\(\)_+=\[\]{}:;'"\\,.\/?\s])*)*)(?::(\d+))?)?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/; 
    var scheme = ['protocol', 'user', 'password', 'hostname', 'host', 'port', 'pathname', 'search', 'hash'], parts = re.exec(str); 

    if (parts != null) { 
     for (var i = 0, l = scheme.length, obj = {}; i < l;) { 
      obj[ scheme[i] ] = parts[++i] != undefined ? parts[i] : ''; 
     } 

     return obj; 
    } 

    return false; 
} 
0

我经常用这个函数从URL解析主机:

function urlParseHost(url){ 
    var re = new RegExp("^(?:f|ht)tp(?:s)?\://([^/]+)", "im"); 
    return(url.match(re)[1].toString()); 
} 

您可以从GitHub here获取工作代码。