window.location, URL에서 값 가져오기

Server side 외에도 Client side에서 URL Query Parameter를 가져와야 하는 경우가 가끔 있다.
필요할 때 꺼내 쓸 수 있게 정리해 봤다.
prototype.js에는 이런 Parameter를 가져오는 method가 있으나 그런 플러그인을 사용하지 않고 값을 가져오는 방식이다.

1. DOM

URL = https://http://www.google.co.kr/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=html5

alert(window.location.hash);     // "#q=html5"
alert(window.location.host);     // "www.google.co.kr"
alert(window.location.hostname); // "www.google.co.kr"
alert(window.location.href);     // "https://www.google.co.kr/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=html5"
alert(window.location.origin);    // "https://www.google.co.kr"
alert(window.location.pathname); // "/webhp"
alert(window.location.port);     // "" (port number)
alert(window.location.protocol);  // "https:"
alert(window.location.search);   // "?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8"

window.location.reload();   // webpage reloaded
window.location.replace();  // 나중에 따로 다루기로 함.
window.location.toString(); // .href와 같은 결과가 나옴.

2. Substr 방식으로 URL 분리

이외에도 url parameter를 가져오는 다른 방법이 있다.

These are all great answers, but I needed something a bit more robust, and thought you all might like to have what I created. It is a simple library method that does dissection and manipulation of url parameters. The static method has the following sub methods that can be called on the subject url:

  • getHost
  • getPath
  • getHash
  • setHash
  • getParams
  • getQuery
  • setParam
  • getParam
  • hasParam
  • removeParam

Example:

URLParser(url).getParam('myparam1')
var url = "http://www.test.com/folder/mypage.html?myparam1=1&myparam2=2#something";

function URLParser(u){
    var path="",query="",hash="",params;
    if(u.indexOf("#") > 0){
        hash = u.substr(u.indexOf("#") + 1);
        u = u.substr(0 , u.indexOf("#"));
    }
    if(u.indexOf("?") > 0){
        path = u.substr(0 , u.indexOf("?"));        
        query = u.substr(u.indexOf("?") + 1);
        params= query.split('&');
    }else
        path = u;
    return {
        getHost: function(){
            var hostexp = /\/\/([\w.-]*)/;
            var match = hostexp.exec(path);
            if (match != null && match.length > 1)
                return match[1];
            return "";
        },
        getPath: function(){
            var pathexp = /\/\/[\w.-]*(?:\/([^?]*))/;
            var match = pathexp.exec(path);
            if (match != null && match.length > 1)
                return match[1];
            return "";
        },
        getHash: function(){
            return hash;
        },
        getParams: function(){
            return params
        },
        getQuery: function(){
            return query;
        },
        setHash: function(value){
            if(query.length > 0)
                query = "?" + query;
            if(value.length > 0)
                query = query + "#" + value;
            return path + query;
        },
        setParam: function(name, value){
            if(!params){
                params= new Array();
            }
            params.push(name + '=' + value);
            for (var i = 0; i < params.length; i++) {
                if(query.length > 0)
                    query += "&";
                query += params[i];
            }
            if(query.length > 0)
                query = "?" + query;
            if(hash.length > 0)
                query = query + "#" + hash;
            return path + query;
        },
        getParam: function(name){
            if(params){
                for (var i = 0; i < params.length; i++) {
                    var pair = params[i].split('=');
                    if (decodeURIComponent(pair[0]) == name)
                        return decodeURIComponent(pair[1]);
                }
            }
            console.log('Query variable %s not found', name);
        },
        hasParam: function(name){
            if(params){
                for (var i = 0; i < params.length; i++) {
                    var pair = params[i].split('=');
                    if (decodeURIComponent(pair[0]) == name)
                        return true;
                }
            }
            console.log('Query variable %s not found', name);
        },
        removeParam: function(name){
            query = "";
            if(params){
                var newparams = new Array();
                for (var i = 0;i < params.length;i++) {
                    var pair = params[i].split('=');
                    if (decodeURIComponent(pair[0]) != name)
                          newparams .push(params[i]);
                }
                params = newparams ;
                for (var i = 0; i < params.length; i++) {
                    if(query.length > 0)
                        query += "&";
                    query += params[i];
                }
            }
            if(query.length > 0)
                query = "?" + query;
            if(hash.length > 0)
                query = query + "#" + hash;
            return path + query;
        },
    }
};


document.write("Host: " + URLParser(url).getHost() + '<br>');
document.write("Path: " + URLParser(url).getPath() + '<br>');
document.write("Query: " + URLParser(url).getQuery() + '<br>');
document.write("Hash: " + URLParser(url).getHash() + '<br>');
document.write("Params Array: " + URLParser(url).getParams() + '<br>');
document.write("Param: " + URLParser(url).getParam('myparam1') + '<br>');
document.write("Has Param: " + URLParser(url).hasParam('myparam1') + '<br>');

document.write(url + '<br>');

// Remove first param
url = URLParser(url).removeParam('myparam1');
document.write(url + ' - Remove first param<br>');

// Add third param
url = URLParser(url).setParam('myparam3',3);
document.write(url + ' - Add third param<br>');

// Remove second param
url = URLParser(url).removeParam('myparam2');
document.write(url + ' - Add third param<br>');

// Add hash 
url = URLParser(url).setHash('newhash');
document.write(url + ' - Set Hash<br>');

// Remove last param
url = URLParser(url).removeParam('myparam3');
document.write(url + ' - Remove last param<br>');

// Remove a param that doesnt exist
url = URLParser(url).removeParam('myparam3');
document.write(url + ' - Remove a param that doesnt exist<br>');


출처: http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript


window.location, URL에서 값 가져오기”에 대한 답글 2개

댓글 남기기