Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

97
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!