Skip to content

Instantly share code, notes, and snippets.

@cvan
Last active February 21, 2024 13:44
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save cvan/38fa77f1f28d3eb9d9c461e1d0d0d7d7 to your computer and use it in GitHub Desktop.
Save cvan/38fa77f1f28d3eb9d9c461e1d0d0d7d7 to your computer and use it in GitHub Desktop.
get query-string parameters (alternative to `URLSearchParams`)
var queryParams = window.location.search.substr(1).split('&').reduce(function (qs, query) {
var chunks = query.split('=');
var key = chunks[0];
var value = decodeURIComponent(chunks[1] || '');
var valueLower = value.trim().toLowerCase();
if (valueLower === 'true' || value === 'false') {
value = Boolean(value);
} else if (!isNaN(Number(value))) {
value = Number(value);
}
return (qs[key] = value, qs);
}, {});
Copy link

ghost commented Jun 7, 2018

Thank You! This helped me!

@ditdemo2019
Copy link

THANK YOU THANK YOU VERY MUCH

@mdtrooper
Copy link

var queryParams = window.location.search.substr(1).split('&').reduce(function (q, query) {
  var chunks = query.split('=');
  var key = chunks[0];
  var value = decodeURIComponent(chunks[1]);
  value = isNaN(Number(value))? value : Number(value);
  return (q[key] = value, q);
}, {});

@cvan
Copy link
Author

cvan commented Feb 26, 2020

@mdtrooper thanks for the suggestions; I updated this gist to coerce numbers as you suggested, in addition to 'true'/'false' to booleans

@petrpacas
Copy link

Appreciated 👍

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