Get all query string values using JavaScript
📅June 22, 2021
In this article, we’ll show you how to get all parameters of the query string from the URL using JavaScript.
Here, we will use the URLSearchParams to get a list of all query params.
Checkout more articles on JavaScript
- Get query string parameters from URL in JavaScript
- Get Current URL in JavaScript
- Find all URLs in a string except the URL inside a and img tag and make a link using JavaScript
- How to open an URL in a new tab using JavaScript
Let’s consider the following URL for example to get a query string parameter values.
const url = 'https://www.cluemediator.com/?search=login%20app&category=reactjs';
Instead of the URL you can also use the current page URL using the `window.location.href`.
Now simply run the following code to get the list of the query parameters in the object.
const urlSearchParams = (new URL(url)).searchParams;
const params = Object.fromEntries(urlSearchParams.entries());
console.log(params);
// Output: {search: "login app", category: "reactjs"}
You can also get the value of the individual parameters. Use the code below.
urlSearchParams.get("search"); // Output: login app
urlSearchParams.get("category"); // Output: reactjs
You can combine all the above code and check the output in the console.
const url = 'https://www.cluemediator.com/?search=login%20app&category=reactjs';
const urlSearchParams = (new URL(url)).searchParams;
const params = Object.fromEntries(urlSearchParams.entries());
console.log(params);
// Output: {search: "login app", category: "reactjs"}
urlSearchParams.get("search"); // Output: login app
urlSearchParams.get("category"); // Output: reactjs
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂