URL objects have both a search
property that shows the query parameters as a single string and searchParams
, a URLSearchParams
object with which you can manage the params without having to think about URL encoding or any nastiness.
const myUrl = new URL("https://example.com/my-page?id=1&q=search%20term#my-fragment");
myUrl.search === "?id=1&q=search%20term"
myUrl.searchParams.get("q") === "search term"
myUrl.searchParams.set("q", "other search term");
// {id: '1', q: 'other search term'}
Object.fromEntries(myUrl.searchParams.entries());
myUrl.search === "?id=1&q=search%20term"
myUrl.searchParams.get("q") === "search term"
myUrl.searchParams.set("q", "other search term");
// {id: '1', q: 'other search term'}
Object.fromEntries(myUrl.searchParams.entries());
Note that window.location
is not a URL object, so while it has search
, it doesn't have searchParams
. In that case, you could do:
const currentUrl = new URL(window.location);
or,
const searchParams = new URLSearchParams(window.location.search);