In a web application that makes use of AJAX calls, I need to submit a request but add a parameter to the end of the URL, for example:
Original URL:
Vianney Bajart's answer is correct; however, URL will only work if you have the complete URL with port, host, path and query:
new URL('http://server/myapp.php?id=10&enabled=true')
And URLSearchParams will only work if you pass only the query string:
new URLSearchParams('?id=10&enabled=true')
If you have an incomplete or relative URL and don't care for the base URL, you can just split by ?
to get the query string and join later like this:
function setUrlParams(url, key, value) {
url = url.split('?');
usp = new URLSearchParams(url[1]);
usp.set(key, value);
url[1] = usp.toString();
return url.join('?');
}
let url = 'myapp.php?id=10';
url = setUrlParams(url, 'enabled', true); // url = 'myapp.php?id=10&enabled=true'
url = setUrlParams(url, 'id', 11); // url = 'myapp.php?id=11&enabled=true'
Not compatible with Internet Explorer.