Created
October 10, 2017 10:59
-
-
Save andyexeter/e8446cc0b7773d0198b2d64fe5a08456 to your computer and use it in GitHub Desktop.
JavaScript function to return a query string as an object
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
function getQuery(query) { | |
query = query || window.location.search; | |
var queryString = {}; | |
var vars = query.split('&'); | |
for (var i = 0; i < vars.length; i++) { | |
var pair = vars[i].split('='); | |
pair[0] = decodeURIComponent(pair[0]); | |
pair[1] = decodeURIComponent(pair[1]); | |
// If first entry with this name | |
if (typeof queryString[pair[0]] === 'undefined') { | |
queryString[pair[0]] = pair[1]; | |
// If second entry with this name | |
} else if (typeof queryString[pair[0]] === 'string') { | |
queryString[pair[0]] = [queryString[pair[0]], pair[1]]; | |
// If third or later entry with this name | |
} else { | |
queryString[pair[0]].push(pair[1]); | |
} | |
} | |
return queryString; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment