본문 바로가기

Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

유령노트

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

# Dev/Javascript

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

유령손 2017. 10. 17. 15:14

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

 

1
2
3
4
5
6
7
8
9
10
11
12
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();  // 나중에 따로 다루기로 함.
cs

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:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
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>');
cs
 
 
참고 출처 : https://hsmtree.postype.com/post/2517

 

'# Dev > Javascript' 카테고리의 다른 글

id 미사용 form 데이터 유효성 검사  (0) 2019.08.22
함수 속도 체크  (0) 2018.04.03
제이쿼리 사용 안하기  (0) 2017.09.28
문자열의 바이트 길이 구하는 방법  (0) 2017.06.21
창 크기가 바뀔 때 마다 실행  (0) 2017.06.13