How do you extract query string parameters from a URL in JavaScript using URLSearchParams?
Passwindow.location.search(or any fullURLobject's.searchParams) into the built-in **URLSearchParams** API and call **.get(“paramName”)`** to retrieve decoded values cleanly.
Extract Parameters from Current Page URL
// Example URL: [https://forum.a1lab.tech/search?q=javascript&page=2](https://forum.a1lab.tech/search?q=javascript&page=2)
const params = new URLSearchParams(window.location.search);
const query = params.get("q"); // "javascript"
const page = params.get("page"); // "2"
const hasSort = params.has("sort"); // false
Parse Parameters from Any URL String
const url = new URL("[https://forum.a1lab.tech/post?id=42&tag=js](https://forum.a1lab.tech/post?id=42&tag=js)");
console.log(url.searchParams.get("id")); // "42" '
You must log in or register to comment.
