Heim  >  Artikel  >  Web-Frontend  >  JavaScript解析浏览器路径的一个方法

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

伊谢尔伦
伊谢尔伦Original
2016-11-22 11:32:571028Durchsuche

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;


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn