Created
June 11, 2010 02:30
-
-
Save mapiondev/433957 to your computer and use it in GitHub Desktop.
[JavaScript] ゲットパラメータ形式の文字列とハッシュオブジェクトの相互変換
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* ゲットパラメータ形式の文字列からハッシュオブジェクトを取得、デリミタは&とホワイトスペース | |
* @param {String} str 処理対象パラメータ文字列 | |
* @param {Boolean} [duplicateToArray] 重複パラメータを配列化する | |
* @returns {Object} ハッシュオブジェクト | |
*/ | |
parameterToHash=function(str,duplicateToArray){ | |
if(str===void 0)str=location.search; | |
var params = str.replace(/^\?/g,"").replace(/\s/g,"&").replace(/&+/g,"&").match(/[^&]*/g); | |
var ret = {}; | |
for(var i=0,l=params.length;i<l;i++){ | |
if(params[i].match(/(.*)=(.*)/)){ | |
var key = RegExp.$1; | |
var val = RegExp.$2; | |
if(duplicateToArray){ // 重複してたらArrayに | |
if(!ret[key]){ | |
ret[key]=val; | |
}else if(typeof ret[key]==="string"){ | |
ret[key]=[ret[key],val]; | |
}else{ | |
ret[key].push(val); | |
}; | |
}else{ // 重複してたら上書き | |
ret[key]=val; | |
}; | |
}; | |
}; | |
return ret; | |
}; | |
/** | |
* ハッシュオブジェクトからゲットパラメータ形式の文字列を取得 | |
* @param {Object} obj 処理対象ハッシュオブジェクト | |
* @returns {String} パラメータ文字列 | |
*/ | |
hashToParameter=function(obj){ | |
if(!obj)return ""; | |
var a=[]; | |
for(var i in obj){ | |
if(obj.hasOwnProperty(i)){ | |
if(obj[i] instanceof Array){ | |
for(var j=0,l=obj[i].length;j<l;j++)a.push(i+"="+obj[i][j]); | |
}else{ | |
a.push(i+"="+obj[i]); | |
}; | |
}; | |
}; | |
return a.join("&"); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment