Skip to content

Instantly share code, notes, and snippets.

@davidhund
Created December 13, 2017 12:24
Show Gist options
  • Save davidhund/36ddef4b9c54790633b60044150e7d98 to your computer and use it in GitHub Desktop.
Save davidhund/36ddef4b9c54790633b60044150e7d98 to your computer and use it in GitHub Desktop.
Get URL parameters from String
/**
* Get URL parameters from String
* source: https://css-tricks.com/snippets/javascript/get-url-variables/
* @param {String} url The URL
* @return {Object} The URL parameters
*/
var getParams = function (url) {
var params = {};
var parser = document.createElement('a');
parser.href = url;
var query = parser.search.substring(1);
if (query) {
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
params[pair[0]] = decodeURIComponent(pair[1]);
}
}
return params;
};
// Usage:
// getParams(window.location.href); // from window URL
// getParams('http://some.url?page=1&id=2'); // from String
@davidhund
Copy link
Author

davidhund commented Dec 13, 2017

The above is a bit oldskool.

A new ES6 way would be e.g.:

function getUrlParams(search) {
  let hashes = search.slice(search.indexOf('?') + 1).split('&')
  return hashes.reduce((params, hash) => {
      let [key, val] = hash.split('=')
      return Object.assign(params, {[key]: decodeURIComponent(val)})
  }, {})
}

There is a better (native way) with URLSearchParams:

See: https://developers.google.com/web/updates/2016/01/urlsearchparams?hl=en

but (IE) support is lacking... (Polyfilled)

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