Home  >  Article  >  Web Front-end  >  A method for JavaScript to parse browser paths

A method for JavaScript to parse browser paths

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

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;


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn