Last active
July 20, 2016 03:04
-
-
Save jacoyutorius/a3717d4807c3b175d4d5f7f659f28d68 to your computer and use it in GitHub Desktop.
Ransackを使ったRailsのgetパラメータをjsで使いやすいようにパースする
This file contains hidden or 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
| function ParamParser(){ | |
| var search_params = decodeURI(window.location.search); | |
| if(search_params == ""){ | |
| return {}; | |
| } | |
| // 検索パラメータの冒頭の"?"を削除 | |
| if(search_params[0] == "?"){ | |
| search_params = search_params.substr(1); | |
| } | |
| // パラメータを配列に入れる | |
| var array = search_params.split("&"); | |
| // 空のパラメータを削除 | |
| array = array.filter(function(row){ if(row != "") return row ;}) | |
| // パラメータを整形し、配列or値毎にObjectの配列に入れる | |
| var hash = {}; | |
| for(var i = 0; i < array.length; i++){ | |
| var keyPair = array[i].split("="); | |
| var key = keyPair[0].substr(1).match(/[^\W]/g).join(""); | |
| var keyIsArray = (keyPair[0].lastIndexOf("[") == keyPair[0].length - 2) | |
| var value = keyPair[1]; | |
| if(hash[key] == undefined){ | |
| // 配列かどうか判定 | |
| if(keyIsArray){ | |
| hash[key] = [value]; | |
| } | |
| else{ | |
| hash[key] = value; | |
| } | |
| } | |
| else{ | |
| hash[key].push(value); | |
| } | |
| } | |
| return hash; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment