Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

98
Vistas
Add extra query param in Javascript whilst keeping original URL

I have a button in body that once clicked, it should add an extra query parameter in the URL.

let addParam;
const button = document.createElement("BUTTON");
button.textContent = "Add";
document.body.prepend(button);

button.addEventListener("click", () => {
  const url = new URL(window.location.href);
  url.searchParams.set("param", "value");

  window.history.pushState({ path: url.href }, "", url.href);
  addParam = addParam ? false : true;
});

It works fine, the problem is that the current URL contains already a query parameter in the form of ?path=path/to/file, so when we set another parameter with set(key, value), it changes the ?path=path/to/file to ?path=path%2Fto%2Ffile. Is there a way I can prevent that from happening and keeping the original URL?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Note that both URLs mean the same thing. I'm guessing you prefer the one with / instead of the encoded form of it because it's more obvious to people reading the URL.

This may vary by browser, but on Chromium-based browsers it seems that it keeps the / if it's in the URL you pass to pushState. It's the URLSearchParams that's encoding the /.

I originally posted a solution doing string concatenation with encodeURIComponent instead, but my solution was doing an append, not a set. Your code is using set. Fortunately I'd also included a second solution: You can convert %2F to / after adding to the search params and converting them to a string:

const { origin, pathname, search } = window.location;
const searchParams = new URLSearchParams(search);
searchParams.set("param", "value");
const paramsString = searchParams.toString().replace(/%2f/gi, "/");
const url = `${origin}${pathname}?${paramsString}`;

window.history.pushState({ path: url }, "", url);
addParam = addParam ? false : true;

Note that I don't advocate this. I'd stick with the code you have. But it's your project, so you get to decide. :-)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda