用javascript进一步解析url主机名

Further parsing of url hostname with javascript

本文关键字:url 主机 javascript 进一步      更新时间:2023-09-26

有很多帖子寻找解析url并获得主机名的方法。通常的解决方案是创建一个文档元素,设置一个url,然后访问.hostname属性。这是一个很好的解决方案。我很难超越这个技巧。

我有一个函数可以成功地从主机名中提取基本主机。为了描述我所说的基本主机(不确定正确的术语),我将展示该函数并给出一些示例输入输出。

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方法是很好的第一步,我只是在寻找一种更好的方法来破解有时在基本级主机之前的子主机。

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

你应该能够分支你的代码基于这样一个事实,即cctld像你的例子中的.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中google之前的位)。

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

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;
}

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

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