Skip to content

Instantly share code, notes, and snippets.

@magician11
Created July 1, 2018 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magician11/5914ae687e8494f5b4718263eef7003e to your computer and use it in GitHub Desktop.
Save magician11/5914ae687e8494f5b4718263eef7003e to your computer and use it in GitHub Desktop.
How to get all parameters from a URL as an associative array
export const getURLparams = () => {
const pl = /\+/g;
const search = /([^&=]+)=?([^&]*)/g;
const decode = s => decodeURIComponent(s.replace(pl, ' '));
const query = window.location.search.substring(1);
const urlParams = {};
let match;
while ((match = search.exec(query))) {
urlParams[decode(match[1])] = decode(match[2]);
}
return urlParams;
};
@magician11
Copy link
Author

Code inspired from https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/2880929#2880929

usage:

if the URL is https://www.google.com/?bob=john&id=123

const params = getURLparams();
console.log(params);
console.log(params['id']);

this would output

Object {bob: "john", id: "123"}
123 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment