Created
May 22, 2014 12:32
-
-
Save Leko/d24b4b811ea6f592030f to your computer and use it in GitHub Desktop.
[js] parse GET parameters
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 parseQuery(query) { | |
return query.split("&").reduce(function(memo, query){ | |
var parts = query.split('='), | |
key = parts[0], | |
val = encodeURIComponent(parts[1]); | |
if(key.indexOf('[]') == key.length-2) { | |
key = key.replace('[]', ''); | |
memo[key] = Array.isArray(memo[key]) ? memo[key] : []; | |
memo[key].push(val); | |
} else { | |
memo[key] = val; | |
} | |
return memo; | |
}, {}); | |
} | |
// PHP like | |
$_GET = parseQuery(location.search); | |
// $_GET['hoge'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment