In this article, we’ll show you how to get query string values 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.
const url = 'https://codepremix.com/?search=color%20picker&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: "color picker", category: "reactjs"}
You can also get the value of the individual parameters. Use the code below.
urlSearchParams.get("search"); // Output: color picker
urlSearchParams.get("category"); // Output: reactjs
You can combine all the above code and check the output in the console.
const url = 'https://codepremix.com/?search=color%20picker&category=reactjs';
const urlSearchParams = (new URL(url)).searchParams;
const params = Object.fromEntries(urlSearchParams.entries());
console.log(params);
// Output: {search: "color picker", category: "reactjs"}
urlSearchParams.get("search"); // Output: color picker
urlSearchParams.get("category"); // Output: reactjs
That’s it for today.
Thank you for reading. Happy Coding..!!