Check if parameter exists in URL javascript

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 any parameter in this URL and with that I can add one more at the end. For example:

  • If URL is www.site.com.br it www.site.com.br/?id=1
  • If URL is www.site.com.br/?utm=teste it 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 can not know exactly what parameter I'll have.

I need to know this, because I need to add a parameter id=SC to the end of the URL and sometimes it is giving error, because a previous parameter already exists. Here's how I'm 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.

    
asked by anonymous 10.09.2018 / 18:25

4 answers

3

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

?qualquer_coisa=

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

var ref = document.referrer;
window.location.href = ref + (/\?.{1,}=/.test(ref) ? '&' : '?') + 'id=CS';
    
10.09.2018 / 18:58
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());
    
10.09.2018 / 20:12
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'
}
    
10.09.2018 / 18:31
1

An alternative is to use new URL(endereco) to create a URL object % and then use a URLSearchParams to manipulate URL parameters.

Using the set method, 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.toString();

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.toString();

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... ), otherwise new URL gives error.

To manipulate the current URL, you can var url = new URL(window.location) . Then you add the parameters you need (using set ) and finally make window.location = url :

var url = new URL(window.location);

var sp = new URLSearchParams(url.search);
sp.set('id', '1')
url.search = sp.toString();

window.location = url;

Obs: If the URL already has a parameter id , set will overwrite its 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.toString();

// 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 id parameter already exists using if (sp.has('id'))

Using regex and adding the parameter at the end may work for most cases, but if the URL has anchors , it will not work.

Ex: http://www.site.com/?teste=1#secao .

If you simply add the parameter at the end, the URL will be http://www.site.com/?teste=1#secao&id=1 , which is invalid. Using URLSearchParams you get the correct result, which is http://www.site.com/?teste=1&id=1#secao .

Currently this API works fine in Firefox, Chrome, Edge and Safari, but not in IE 11: link

p>     
10.09.2018 / 18:45