Check for parameter in javascript URL

Asked

Viewed 1,201 times

1

I have a URL that may or may not contain parameters in it. Ex: www.site.com.br/?id=1 or www.site.com.br.

I need to check if there is a parameter in this URL and with that I can add one more at the end. For example:

  • If URL is www.site.com.br flipped www.site.com.br/?id=1
  • If URL is www.site.com.br/?utm=teste flipped www.site.com.br/?utm=teste&id=1

That is, the URL may or may not have a parameter and this parameter may be random, so I have no way of knowing exactly what parameter will have.

I need to know this because I need to add a parameter id=SC at the end of the URL and sometimes is giving error, because there is already a previous parameter. See how I am doing:

//Pego a url anterior que o usuário estava e redireciono para a mesma url porém adicionando um parametro no final    
window.location.href = document.referrer+'?id=CS';

With the above code, if the previous URL is www.site.com.br/?utm=teste the new URL will be site.com.br/?utm=teste?id=CS and the user will not be able to access the page.

4 answers

4

Just use SearchParams.set().

var url="";

//COM parametro id na url, substitui o valor
url = new URL('http://www.site.com.br/?utm=teste&id=12');
   url.searchParams.set('id', 'SC');
    console.log(url.toString());

//SEM parametro id na url, acrescenta o parametro e respectivo valor
// já separado com &
url = new URL('http://www.site.com.br/?utm=teste');
    url.searchParams.set('id', 'SC');
    console.log(url.toString());
    
//SEM parametros na url acrescenta o parametro e respectivo valor
//com a interrogação (?)
url = new URL('http://www.site.com.br');
    url.searchParams.set('id', 'SC');
    console.log(url.toString());

 // com anchor
   url = new URL('http://www.site.com.br/?utm=teste&id=12#secao');
   url.searchParams.set('id', 'SC');
    console.log(url.toString());

  • It’s a solution too, but I don’t like these Apis because it doesn’t work in Ieca.

  • 3

    @sam hahaha, just do it like this: if(isIE == true){ use do do tio sam}Else{use o do vô leo} :)

2

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

  • If you want to take the domain dynamically, you can also use the document.domain, in case you don’t want something fixed in the new URL.

1

I think your own logic already indicates that what you need to do is an if. Ex:

if(document.referrer.contains("/?")){
window.location.href = document.referrer+'?id=CS'
}
else{
window.location.href = document.referrer+'&id=CS'
}
  • but what if the previous url is for example: site.com.br/test/p? utm=test ie, I can’t put a fixed rule...I could only search if there is a "?" in the url, but I don’t know if it would be right

  • Because the url of this page is friendly, IE, each one is a way. Will the friendly url has "?" I find difficult, but will know but

1


You can check with regex if no document.referrer has the standard:

?qualquer_coisa=

If true, concatenate &, if false, concatenate ?:

var ref = document.referrer;
window.location.href = ref + (/\?.{1,}=/.test(ref) ? '&' : '?') + 'id=CS';

Browser other questions tagged

You are not signed in. Login or sign up in order to post.