Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
How to pass/append url parameter to all hrefs (links) on a page?

Using javascript, my objective is to query the URL and append parameters to all links on a page. If the link already contains a parameter, the link will append the new parameters:

User access page:https://example.com/?location=brazil
Link on page was: https://link.com/?hello=ok
Link becomes: https://link.com/?hello=ok&location=brazil

If there's no previous parameter on link, it becomes:
https://link.com/?location=brazil

I tried the following code:

var queryString = new URL(window.location).search;
document.querySelectorAll("[href]").forEach(link => {
    var current = link.href;
    link.href = current + queryString;
});
</script>

But when a link already contains a parameter, it uses ? instead of & so it becomes:

https://link.com/?hello=ok?location=brazil

How do I solve this problem?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You could just check if the queryString variable contains a ? and replace it with a & instead.

So your code would be something like

var queryString = new URL(window.location).search;
document.querySelectorAll("[href]").forEach(link => {
    var current = link.href;
    const queryStrToUse = queryString.replace('?', '&')
    link.href = current + queryStrToUse;
});
about 4 years ago · Juan Pablo Isaza Relatório

0

It is not a good idea to change the anchor href attribute with javascript for many reasons, but if this is a must you can do:

document.querySelectorAll("a").forEach(link => {
link.href = link.href.includes("?") ? link.href + queryString.replace("?", "&") : link.href + queryString; });
about 4 years ago · Juan Pablo Isaza Relatório

0

var queryString = new URL(window.location).search;
document.querySelectorAll("[href]").forEach(link => {
    var current = link.href;
    link.href = `${current}${current.includes('?') ? queryString.replace('?', '&') : queryString}`;
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda