// 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.
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"> ```