Skip to content

Instantly share code, notes, and snippets.

@clayperez
Created January 17, 2018 18:41
Show Gist options
  • Save clayperez/eaa6d551c9dab97cfd4e72af9c4c75ea to your computer and use it in GitHub Desktop.
Save clayperez/eaa6d551c9dab97cfd4e72af9c4c75ea to your computer and use it in GitHub Desktop.
JAVASCRIPT QUERY STRING PARSING
<script src="https://cdn.jsdelivr.net/jquery/3.1.1/jquery.min.js"></script>
<script>
/// Convert query string to JSON
function getJsonFromUrl(hashBased) {
var query;
if(hashBased) {
var pos = location.href.indexOf("?");
if(pos==-1) return [];
query = location.href.substr(pos+1);
} else {
query = location.search.substr(1);
}
var result = {};
query.split("&").forEach(function(part) {
if(!part) return;
part = part.split("+").join(" "); // replace every + with space, regexp-free version
var eq = part.indexOf("=");
var key = eq>-1 ? part.substr(0,eq) : part;
var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
var from = key.indexOf("[");
if(from==-1) result[decodeURIComponent(key)] = val;
else {
var to = key.indexOf("]");
var index = decodeURIComponent(key.substring(from+1,to));
key = decodeURIComponent(key.substring(0,from));
if(!result[key]) result[key] = [];
if(!index) result[key].push(val);
else result[key][index] = val;
}
});
return result;
}
$(function(){
var tableHtml = "<div class='queryrow header'><div class='querycell'>Field</div><div class='querycell'>Value</div></div>";
var queryJson = getJsonFromUrl();
if(queryJson["confirmation_html"]) { $("#confirmationhtml").text( queryJson["confirmation_html"] ); }
for(var param in queryJson){
if(param !== "" && queryJson[param] !== "" && param !== "confirmation_html"){
tableHtml += "<div class='queryrow'><div class='querycell left'>"+param+"</div><div class='querycell right'>"+queryJson[param]+"</div></div>";
}
}
$("#querycontainer").empty().append(tableHtml);
$(".queryrow").css("word-wrap","break-word");
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment