재우니의 블로그

jQuery 로 구현한  url 파싱하는 방법

 

 

$(document).ready(function () {

    var url = 'http://jquerybyexample.net/codes/code-repository?id=12#top';

    //Create a new link with the url as its href:

    var a = $('<a>', {

        href: url

    });

    var sResult = '<b>Protocol:</b> ' + a.prop('protocol') + '<br/>'     + '<b>Host name: </b>' + a.prop('hostname') + '<br/>' 

    + '<b>Path: </b>' + a.prop('pathname') + '<br/>' 

    + '<b>Query: </b>' + a.prop('search') + '</br>' 

    + '<b>Hash: </b>' + a.prop('hash');

    

    $('span').html(sResult);

});

 

Protocol: http:
Host name: jquerybyexample.net
Path: /codes/code-repository
Query: ?id=12
Hash: #top

 

url 을 window.location.search.substring 통해 가져와서 파싱하는 함수이다.

 

var getUrlParameter = function getUrlParameter(sParam) {

    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;


    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};

 

만약에 접속하는 url 이 http://intra2.univ.me/Admin/BoardArpAuth?analy=10001 경우, 10001 을 alert 띄울 겁니다.

jQuery 가 필요하면... 를 통해 ready() 구문 안에 작업하시면 됩니다.

 

<script   src="https://code.jquery.com/jquery-2.2.4.min.js"   integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="   crossorigin="anonymous"></script>



$(function () {

  var analy = getUrlParameter('analy');

  alert(analy); //10001

});