Get all query string values using JavaScript
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
Let’s consider the following URL for example to get a query string parameter values.
1 | 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.
1 2 3 4 5 | 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.
1 2 | 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.
1 2 3 4 5 6 7 8 9 10 | 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..!! 🙂