Skip to content

Instantly share code, notes, and snippets.

@whoisryosuke
Created April 22, 2019 02:01
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 whoisryosuke/2fec87d08a913711dfe85d72d03b964e to your computer and use it in GitHub Desktop.
Save whoisryosuke/2fec87d08a913711dfe85d72d03b964e to your computer and use it in GitHub Desktop.
JS - Get URL parameters - via: https://davidwalsh.name/query-string-javascript
// Assuming "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);

console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"

URLSearchParams also provides familiar Object methods like keys(), values(), and entries():

var keys = urlParams.keys();
for(key of keys) { 
  console.log(key); 
}
// post
// action

var entries = urlParams.entries();
for(pair of entries) { 
  console.log(pair[0], pair[1]); 
}

URLSearchParams reminds me a lot of the classList API -- very simple methods yet very useful.

JavaScript Fallback

While URLSearchParams is ideal, not all browsers support that API. There's a polyfill available but if you want a tiny function for basic query string parsing, the following is a function stolen from the A-Frame VR toolkit which parses the query string to get the key's value you'd like:

function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

With the function above, you can get individual parameter values:

getUrlParameter('post'); // "1234"
getUrlParameter('action'); // "edit"
> ```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment