An alternative is to use new URL(endereco)
to create an object URL
and then use a URLSearchParams
to manipulate URL parameters.
By the method set
you can add the new parameter. Then just update it in the URL:
// URL sem parâmetros
var url = new URL('http://www.site.com.br');
var sp = new URLSearchParams(url.search);
sp.set('id', '1')
url.search = sp;
console.log(url.toString()); // http://www.site.com.br/?id=1
//--------------------------------------
// URL com parâmetro
url = new URL('http://site.com.br/teste/p?utm=teste');
sp = new URLSearchParams(url.search);
sp.set('id', '1')
url.search = sp;
console.log(url.toString()); // http://site.com.br/teste/p?utm=teste&id=1
The detail is that the address must have the protocol (http://etc...
, https://etc...
, ftp://etc...
), otherwise new URL
gives error - ie, new URL('http://www.abc.com')
and new URL('https://www.abc.com')
works, but new URL('www.abc.com')
makes a mistake.
To manipulate the current URL, you can do var url = new URL(window.location)
. Then you add the parameters you need (using set
) and finally makes window.location = url
:
var url = new URL(window.location);
var sp = new URLSearchParams(url.search);
sp.set('id', '1')
url.search = sp;
window.location = url;
Obs: if the URL already has a parameter id
, the set
will overwrite your value:
// já tem id=2
var url = new URL('http://www.site.com.br/?id=2');
var sp = new URLSearchParams(url.search);
sp.set('id', '1')
url.search = sp;
// sobrescreve o valor de id para 1
console.log(url.toString()); // http://www.site.com.br/?id=1
If this is the case, you can check if the parameter already exists id
using if (sp.has('id'))
Using regex and adding the parameter at the end can work for most cases, but if the URL has anchovy, won’t work. That’s because the anchovy is at the end (see here and here).
For example, if the URL is http://www.site.com/?teste=1#secao
. If I simply add the parameter at the end, the URL will be http://www.site.com/?teste=1#secao&id=1
, which is not what is desired, since in this case the id=1
is not part of the query string. Using URLSearchParams
you get the right result, which is http://www.site.com/?teste=1&id=1#secao
, see:
// tem anchor "#secao"
var url = new URL('http://www.site.com/?teste=1#secao');
var sp = new URLSearchParams(url.search);
sp.set('id', '1')
url.search = sp;
// adiciona o id na posição correta (antes do anchor)
console.log(url.toString()); // http://www.site.com/?teste=1&id=1#secao
Just to make the difference clearer:
// tem anchor "#secao"
var url = new URL('http://www.site.com/?teste=1&id=1#secao');
var sp = new URLSearchParams(url.search);
// imprime teste=1 e id=1
for (var [nome, valor] of sp.entries()) {
console.log(`${nome}=${valor}`);
}
console.log(url.hash); // #secao
console.log('----------------');
// se adicionar o parâmetro depois do anchor, não funciona
url = new URL('http://www.site.com/?teste=1#secao&id=1');
sp = new URLSearchParams(url.search);
// só vai imprimir teste=1
for (var [nome, valor] of sp.entries()) {
console.log(`${nome}=${valor}`);
}
// tudo que está depois do # é o anchor
console.log(url.hash); // #secao&id=1
Note that when the URL is http://www.site.com/?teste=1#secao&id=1
, only the teste
is recognised as a parameter of query string. Already everything that is after the #
(in the case, secao&id=1
) is part of the anchovy (that is, if you just concatenate &id=1
at the end of the string, this is not recognized as a parameter).
That’s why concatenating at the end is not guaranteed to work in 100% of cases.
Currently, this API works well on Firefox, Chrome, Edge and Safari, but not on IE 11: https://caniuse.com/#search=Urlsearchparams
It’s a solution too, but I don’t like these Apis because it doesn’t work in Ieca.
– Sam
@sam hahaha, just do it like this: if(isIE == true){ use do do tio sam}Else{use o do vô leo} :)
– user60252