How to get query string values in JavaScript
📅June 30, 2022
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.
- JavaScript Window Navigator Object
- How to get day name from Date in JavaScript
- Open URL in New Tab using JavaScript
- How to Copy to Clipboard in JavaScript
- JavaScript Convert 12 Hour AM/PM Time to 24 Hour Time Format
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..!!