Skip to content

Instantly share code, notes, and snippets.

@debendraoli
Last active September 17, 2019 06:43
Show Gist options
  • Save debendraoli/cd5a953fe8750524cc6757b8f9a09e68 to your computer and use it in GitHub Desktop.
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.
// @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