Djave
Djave

Reputation: 9329

How to replace URLSearchParams and get full URL after modification

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?

Upvotes: 4

Views: 7750

Answers (3)

Lianel
Lianel

Reputation: 159

I like to use this function

const buildParams = (filters) => {
  const params = new URLSearchParams()
  Object.entries(filters).forEach(([filterName, filterValue]) => {
    if (Array.isArray(filterValue)) {
      params.append(filterName, filterValue.join(','))
    } else if (filterValue) {
      params.append(filterName, filterValue)
    }
  })
  return params.toString()
}

Of course could be more complex.

Upvotes: 1

Ath.Bar.
Ath.Bar.

Reputation: 306

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.

Upvotes: 0

ryeballar
ryeballar

Reputation: 30088

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);

Upvotes: 5

Related Questions