标签:
首先我们看看实例
 a.href = ‘http://www.cnblogs.com/wayou/p/‘;
 console.log(a.host);
控制台会输出 "www.cnblogs.com"
所以我们可以利用此特性进行拓展,制作一个更加健壮的解析器。
在此先介绍Location 对象(即url)属性:
| 属性 | 描述 | 
|---|---|
| hash | 设置或返回从井号 (#) 开始的 URL(锚)。 | 
| host | 设置或返回主机名和当前 URL 的端口号。 | 
| hostname | 设置或返回当前 URL 的主机名。 | 
| href | 设置或返回完整的 URL。 | 
| pathname | 设置或返回当前 URL 的路径部分。 | 
| port | 设置或返回当前 URL 的端口号。 | 
| protocol | 设置或返回当前 URL 的协议。 | 
| search | 设置或返回从问号 (?) 开始的 URL(查询部分)。 | 
function parseURL(url) {
    var a =  document.createElement(‘a‘);
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(‘:‘,‘‘),
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function(){
            var ret = {},
                seg = a.search.replace(/^\?/,‘‘).split(‘&‘),
                len = seg.length, i = 0, s;
            for (;i<len;i++) {
                if (!seg[i]) { continue; }
                s = seg[i].split(‘=‘);
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,‘‘])[1],
        hash: a.hash.replace(‘#‘,‘‘),
        path: a.pathname.replace(/^([^\/])/,‘/$1‘),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,‘‘])[1],
        segments: a.pathname.replace(/^\//,‘‘).split(‘/‘)
    };
}
标签:
原文地址:http://www.cnblogs.com/so-letitgo/p/4499394.html