0

There are a lot of posts looking for way to parse a url and get the hostname. The normal solution is to create a document element, set a url, and access the .hostname property. It's a great solution. I'm having trouble going a bit beyond this technique.

I have a function which successfully extracts the base host from a hostname. To describe what I mean by base host (not sure the correct nomenclature) I will show the function and give some example input outputs.

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 

The last example is the exception I fear, and why I'm looking for a more viable solution. The .hostname method for getting a host is a great first step, I just am looking for a better method of hacking off the sub-hosts that sometimes precede the base level host.

Any help appreciated (if only correcting my terminology).

4

4 回答 4

0

您应该能够根据.uk示例中的 ccTLD 始终为 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 中的 google 之前的位)。

于 2013-01-13T16:46:39.860 回答
0
function parseURL(str) {
    var re = /^(?:([a-zA-Z]+:)\/\/)?(?:([-+._a-zA-Z0-9]+)(?::([-+._a-zA-Z0-9]+))?@)?(([^-~!@#$%^^&*\(\)_+=\[\]{}:;'"\\,.\/?\s]+(?:[^~!@#$%^^&*\(\)_+=\[\]{}:;'"\\,.\/?\s]+[^-~!@#$%^^&*\(\)_+=\[\]{}:;'"\\,.\/?\s])*(?:\.[^-~!@#$%^^&*\(\)_+=\[\]{}:;'"\\,.\/?\s]+(?:[^~!@#$%^^&*\(\)_+=\[\]{}:;'"\\,.\/?\s]+[^-~!@#$%^^&*\(\)_+=\[\]{}:;'"\\,.\/?\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;
}
于 2013-05-10T23:27:31.140 回答
0

当我想解析一个 URL 时,我会做这样的事情

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(或从函数中删除其余部分)

于 2013-01-13T17:04:01.570 回答
0

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

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

您可以在此处从 GitHub 获取工作代码。

于 2014-10-09T18:25:01.397 回答