skip to Main Content

I have this code that I’m trying to condense:

const urlParams = new URLSearchParams(window.location.search);
urlParams.set('order', 'dates');
window.location.search = urlParams;

My first attempt was to write:

window.location.search = (new URLSearchParams(window.location.search)).set('order', 'dates');

But this just redirects me to /?undefined

After some digging I understood that this does not return the modified URLSearchParams object, but just the return value of the URLSearchParams.set() method which is always undefined.

What options to I have to make this code as short as possible, to inline it into an HTML elements onclick attribute?

2

Answers


  1. The code works well without any compression.

    I wouldn’t recommend to minify it manually. I guess some bundlers could compress JS inside html like in onclick attributes.

    <button onclick="const params = new URLSearchParams(window.location.search); params.set('order', 'dates'); window.location.search = params;">Navigate</button>

    A minified version could be:

    <button onclick="l=location;p=new URLSearchParams(l.search);p.set('order','dates');l.search=p">Navigate</button>
    Login or Signup to reply.
  2. The code cannot be compressed (according to my perspective). If anyone gets any way to compress it, I would be happy that someone has put their time and shown up to answer the question. Also, inform me too in the comments.

    But this all can be squished into one (ugly) line:

    window.location.search = (() => {let u = new URLSearchParams(window.location.search);u.set('order', 'dates'); return u;})();
    

    Not completely sure, but this should work. Inform me if it works or not 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search