URL parameters (also called query string parameters or URL variables) are used to send small amounts of data from page to page, or from client to server via a URL. They can contain all kinds of useful information, such as search queries, link referrals, product information, user preferences, and more. |
In modern browsers, this has become a lot easier, thanks to the URLSearchParams interface. This defines a host of utility methods to work with the query string of a URL. |
Assuming that our URL is https://example.com/?product=shirt&color=blue&newuser&size=m, we can grab the query string using window.location.search:
const queryString = window.location.search; console.log(queryString); // ?product=shirt&color=blue&newuser&size=m |
We can then parse the query string’s parameters using URLSearchParams:
const urlParams = new URLSearchParams(queryString); |
Then we call any of its methods on the result. For example, URLSearchParams.get() will return the first value associated with the given search parameter: const product = urlParams.get('product') console.log(product); // shirt const color = urlParams.get('color') console.log(color); // blue const newUser = urlParams.get('newuser') console.log(newUser); // empty string |
Use the Object.fromEntries method and pass the URLSearchParams instance as an argument. This creates a JavaScript object from the parsed query parameters:
const params = Object.fromEntries( new URLSearchParams(window.location.search) ) // URL: example.com/path?foo=bar&name=futurestudio&num=1 // { foo: 'bar', name: 'futurestudio', num: '1' } |
Checking for the Presence of a Parameter You can use URLSearchParams.has() to check whether a certain parameter exists: console.log(urlParams.has('product')); // true console.log(urlParams.has('paymentmethod')); // false |
Getting All of a Parameter’s Values You can use URLSearchParams.getAll() to return all of the values associated with a particular parameter: console.log(urlParams.getAll('size')); // [ 'm' ] //Programmatically add a second size parameter. urlParams.append('size', 'xl'); console.log(urlParams.getAll('size')); // [ 'm', 'xl' ] |
Iterating over Parameters URLSearchParams also provides some familiar Object iterator methods, allowing you iterate over its keys, values and entries: const keys = urlParams.keys(), values = urlParams.values(), entries = urlParams.entries(); for (const key of keys) console.log(key); // product, color, newuser, size for (const value of values) console.log(value); // shirt, blue, , m for(const entry of entries) { console.log(`${entry[0]}: ${entry[1]}`); } // product: shirt // color: blue // newuser: // size: m |
Showing posts with label url-parameters. Show all posts
Showing posts with label url-parameters. Show all posts
Tuesday, February 7, 2023
How to Get URL Parameters with JavaScript
Subscribe to:
Posts (Atom)