How to replace URLSearchParams and get full URL after modification

Viewed 823

In this situation:

let url = new URL(link.url);
let params = new URLSearchParams(url.search);
params.append("collection", this.collection);

I can call params.toString() to get the final search params. How best can I get the full URL?

console.log(url)

Gets me:

hash: ""
host: "stackoverflow.dev"
hostname: "stackoverflow.dev"
href: "http://stackoverflow.dev/media?page=2"
origin: "http://stackoverflow.dev"
password: ""
pathname: "/media"
port: ""
protocol: "http:"
search: "?page=2"
searchParams: URLSearchParams {}
username: ""

Is it recommended to manually rebuild the URL, i.e:

[url.origin, url.pathname, '?', params.toString()].join('');

Or is there an inbuilt function for applying the updated search params?

2 Answers

You can use the url.searchParams property to set or append a query string in an existing URL instance.

const url = new URL('https://www.sample.com?a=1');

url.searchParams.append('b', '2');

console.log(url);

Try url.origin + url.pathname + "?" + params.toString() (as you said) to use it for the same URL as the document. It logs the location of the document, then a "?" and then the search params. If you want to see it for an external URL, then use url.origin + url.pathname + "?" + url.search.substring(1) + "&" + params.toString();.

But you can also use url.searchParams.append() instead of making a new params variable. Every URL object contains a URLSearchParams object.

Related