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

Popular posts from this blog

CSS Как прикрепить слой (div) к краю

MySQL - How to add JSON column type

Как сделать заголовок модуля активной ссылкой в Joomla 1.5