How to add url params to a static url?

Viewed 33

I have this address 'http://www.example.com' I want to add 'fileName=samplefile' url parameter to my static url (http://www.example.com).

const myUrl = new URL('https://example.com);

myUrl.searchParams.append('fileName', 'samplefile');

I tried this approach and that didn't work.

2 Answers

Just change the string in the first line and add the URL parameters as specified in the http querystring definition.

const myUrl = new URL('https.//example.com?fileName=samplefile');
console.log(myUrl.search);

Check out the specification of URL as well, to learn more about that.

You can use a combination of two methods: URL & URLSearchParams

Example:

var url = new URL("https://example.com");

// If you expected result like this "http://example.com/?fileName=samplefile"
url.searchParams.append('fileName','samplefile');
console.log(url.href);//"http://example.com/?fileName=samplefile"

You can use url.href to get the full URL

You could also use URLSearchParams

let url = new URL("https://example.com");

const urlParams = new URLSearchParams();
urlParams.set('fileName', 'samplefile');

url.search = urlParams;
console.log(url.href);//"http://example.com/?fileName=samplefile"
Related