Dev Tips : URLSearchParams

Your friendly Querystring Helper built right into Javascript

Posted on July 15, 2021

This is one of those things that you don't know exists until you do, and then you'll wonder why you never used it before. URLSearchParams has been around forever in browsers, and supported by all major browsers, but being a predominantly Back End Developer I've never come across it until recently.

It can be used standalone on a string to parse the querystrings, and even lets you iterate through it. For example it can be used for a bunch of useful operation on querystrings - like adding, deleting, updating, sorting, finding and even iterating through these in a foreach loop

Adding, updating or Deleting Querystrings

    const url = new URL('https://website.com?foo=abc&bar=123');
    const params = new URLSearchParams(url.search);
    params.set('page', 3);

It really comes in handy when you use the window.location and window.location.search properties, which give you access to the full URL as well as just the querystring portion.

Working with Page URL

We can also read the current page URL and append querystrings to it using window.location (which includes the url + querystring) and window.location.search (which has just the querystring part).

 
    var ipUrl = window.location;
    const params = new URLSearchParams(ipUrl.search);
    params.set('foo', 123);
    params.set('bar', 'abc');
    window.location.search = params.toString();

I have a working example of this in the sibling git repo which goes along with this page : 2_URLSearchParams-Querystring_API_in_Javascript.html