首页 > web前端 > js教程 > 正文

JavaScript解析浏览器路径的一个方法

伊谢尔伦
发布: 2016-11-22 11:32:57
原创
1031 人浏览过

JavaScript中有时需要用到当前的请求路径等涉及到url的情况,正常情况下我们可以使用location对象来获取我们需要的信息,本文从另外一个途径来解决这个问题,而且更加巧妙

方法如下:

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(&#39;=&#39;);
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,&#39;&#39;])[1],
        hash: a.hash.replace(&#39;#&#39;,&#39;&#39;),
        path: a.pathname.replace(/^([^\/])/,&#39;/$1&#39;),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,&#39;&#39;])[1],
        segments: a.pathname.replace(/^\//,&#39;&#39;).split(&#39;/&#39;)
    };
}
登录后复制

使用方法如下:

var myURL = parseURL(&#39;http://abc.com:8080/dir/index.html?id=255&m=hello#top&#39;);
myURL.file; // = &#39;index.html&#39;
myURL.hash; // = &#39;top&#39;
myURL.host; // = &#39;abc.com&#39;
myURL.query; // = &#39;?id=255&m=hello&#39;
myURL.params; // = Object = { id: 255, m: hello }
myURL.path; // = &#39;/dir/index.html&#39;
myURL.segments; // = Array = [&#39;dir&#39;, &#39;index.html&#39;]
myURL.port; // = &#39;8080&#39;
myURL.protocol; // = &#39;http&#39;
myURL.source; // = &#39;http://abc.com:8080/dir/index.html?id=255&m=hello#top&#39;
登录后复制


相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!