Last active
September 17, 2019 06:43
-
-
Save debendraoli/cd5a953fe8750524cc6757b8f9a09e68 to your computer and use it in GitHub Desktop.
This JavaScript function returns object with key value pairs primarily made for reactjs to get query string but it works with others too.
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
// @author github.com/debendraoli | |
function getQueryString(querystring) { | |
//check & remove "?" and split each query using "&" | |
const string = (querystring.substr(0, 1) === "?" ? querystring.substr(1) : querystring).split('&'); | |
// generate tuple ["query", "string"] by spliting query: query=string | |
// return the object as key value pairs using built-in object.fromEntries | |
return Object.fromEntries(string.map(string => string.split("="))); | |
} | |
// getQueryString("?sortby=newest&approved=true") | |
// {sortby: "newest", approved: "true"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment