JavaScript가 브라우저 경로를 구문 분석하는 방법

伊谢尔伦
풀어 주다: 2016-11-22 11:32:57
원래의
1028명이 탐색했습니다.

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 학습자의 빠른 성장을 도와주세요!