분류 javascript

URL을 파싱하는 JavaScript 함수 작성하시오.

컨텐츠 정보

  • 조회 880 (작성일 )

본문

코드 :

function parse_URL(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('/')
    };
}

console.log(parse_URL('https://365ok.co.kr/bbs/board.php?bo_table=okdown&wr_id=772&page=4'));


결과 :

  1. {source"https://365ok.co.kr/bbs/board.php?bo_table=okdown&wr_id=772&page=4"protocol"https"host"365ok.co.kr"port""query"?bo_table=okdown&wr_id=772&page=4", …}
    1. file:"board.php"
    2. hash:""
    3. host:"365ok.co.kr"
    4. params:
      1. bo_table:"okdown"
      2. page:"4"
      3. wr_id:"772"
      4. __proto__:Object
    5. path:"/bbs/board.php"
    6. port:""
    7. protocol:"https"
    8. query:"?bo_table=okdown&wr_id=772&page=4"
    9. relative:"/bbs/board.php?bo_table=okdown&wr_id=772&page=4"
    10. segments:Array(2)
      1. 0:"bbs"
      2. 1:"board.php"
      3. length:2
      4. __proto__:Array(0)
    11. source:"https://365ok.co.kr/bbs/board.php?bo_table=okdown&wr_id=772&page=4"
    12. __proto__:Object