Getting Query String Parameters in JavaScript... the New Way

by Michael Szul on

People complain a lot about JavaScript, but I think that many of these people are stuck in the past. Not only does JavaScript have a great number of new language features that make it more robust, but there are also many new browser APIs and methods that limit the frustration with web development.

Ever need to get query string parameters in JavaScript?

A basic URL parser could look something like this:

function querystring(obj) {
          const result = [];
          let match;
          const re = new RegExp('(?:\\?|&)' + obj + '=(.*?)(?=&|$)', 'gi');
          while ((match = re.exec(document.location.search)) !== null) {
              result.push(match[1]);
          }
          return result;
      }
      

You'd then get a parameter via:

const name = querystring("name")[0];
      

This assumes you have a query string parameter of name. Notice that this is an array, since you can have multiple parameters with the same name in the query string.

This lets us get a query string parameter, but it's limited in many ways, and requires a lot of custom work for additional functionality.

Thanks to newer Web API methods, you can now accomplish this with URLSearchParams.

The following code accomplishes the same as the above method:

const params = new URLSearchParams(window.location.search);
      const name = params.get("name");
      

The reason you pass in the window.location.search is because this method works on any string in a query string format (key value pairs with ampersands).

This interface is valuable because it doesn't only allow you to get parameters. You can use methods like append(), delete(), has(), and set() to manipulate the collection.

Remember in the first example where we had to use an array because of the possibility of multiple parameters with the same name? With URLSearchParams, you can use the getAll() to capture all of the parameters with the same name.