javascript 에서 URL Query Parameter를 가져와야 하는 경우가 있다.

필요할 때 꺼내 쓸 수 있게 정리해 봤다.

prototype.js에는 이런 Parameter를 가져오는 method가 있으나 그런 플러그인을 사용하지 않고 값을 가져오는 방식이다.

 

1. DOM

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

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


var pathname = window.location.pathname;	// "/sub/webhp.html"
var filename = pathname.substring(pathname.lastIndexOf("/") + 1);	// "webhp.html"
var foldername = pathname.substring(0,pathname.lastIndexOf("/"));	// "/sub"
var baseurl = window.location.origin + "/" + foldername; // "https://www.google.co.kr:443/sub"


window.location.reload();   // 현재 페이지 새로고침
window.location.assign();   // 새로운 주소로 이동
window.location.replace();  // 새로운 주소로 이동(세션히스토리가 남지않아 back불가함)
window.location.toString(); // .href와 같은 결과가 나옴.

 

2. URL에서 parameter를 추가/제거 하는 소스

이외에도 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
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>');

 

 

3. URL에서 parameter를 추가/제거 하는 간단한 버전

  좀 더 간단하게 만든 url parameter를 가져오는 함수와 추가하는 함수이다.

var queryString = (function(){
    "use strict";

    var result = {},
        query = window.location.search.substring(1),
        vars = query.split('&'),
		i,length,
		nameValuePair,arr,key,value;

	for (i = 0, length = vars.length; i < length; i++) {
		nameValuePair = vars[i].split('=');
		key = nameValuePair[0];
		value = decodeURIComponent(nameValuePair[1]);

		if (typeof result[key] === 'undefined') {
			result[key] = value;
		} else if (typeof result[key] === 'string') {
			arr = [result[key], value];
			result[key] = arr;
		} else {
			result[key].push(value);
		}
	}

    return result;
})();



////
//	파라미터 추가하기
//
// 기능 : 기존 URL 파라미터(queryString) 에 새로운 파라미터를 추가함
//     			만일 기존값이 이미 있다면 변경하지 않는다.(브라우저에서 입력한 값에 우선권을 줌)
//	사용예 : queryString = queryStringAppend(queryString, "aa=1&bb=two&cc=셋");
////
function queryStringAppend(result, query){
	query = query||'';
	query = query.replace(/(^\s*)|(\s*$)/g, "");	//trim
	if(query =='') return result;

	var vars = query.split('&'),
		i,length,
		nameValuePair,arr,key,value;

	for (i = 0, length = vars.length; i < length; i++) {
		nameValuePair = vars[i].split('=');
		key = nameValuePair[0];
		value = decodeURIComponent(nameValuePair[1]);

		if (typeof result[key] === 'undefined') {
			result[key] = value;
		}else if(typeof result[key] === 'string' && ( result[key] === '' || result[key] === 'undefined')) {
			result[key] = value;
		}
	}

	return result;
}


function addParams(url, param){
    return url + ( (url.indexOf("?")<0) ? "?":"&" ) + param;
}

 

 

 

 

 

참고 : https://hsmtree.postype.com/post/2517

 

  1. 1111 2022.05.04 11:00

    배차일정

+ Recent posts