Javascript - How to build URL with query parameters
If we just need to add GET parameters to current URL:
Firstly, let`s create URL object with current link.
const url = new URL(window.location.protocol+window.location.host+window.location.pathname);
Where:
window.location.protocol - https or http;
window.location.host - current host;
window.location.pathname - current url after host and before query parameter;
After that, let`s add necessary query parameters:
url.searchParams.set('id', 123);
And get URL what we wanted:
url.toString();
For example, let`s redirect to new URL:
window.location.href = url.toString();
Comments