Parse URL parameters with JavaScript

How many more times will I google it… It’s time to prepare a URL parameters parser implementation that I can easily reuse.

Let’s start with the basics. The problem consists of 3 parts:

  • number one is, of course, parsing the parameters
  • number two is making it work in all browsers
  • three is making sure that when parameters change, script knows about it

URLSearchParams to the rescue

Finally, there is something that works in all browsers. Let’s get straight to it:

function getUrlParam(param) {
  let urlSearchParams = new URLSearchParams(window.location.search);
  return urlSearchParams.get(param);
}

While this looks ok, there are things that have to be improved. First, we need to make sure we don’t construct a new URLSearchParams object if there’s no need for that. Imagine us doing this:

if (getUrlParam('page') && getUrlParam('pages')) {
  var page = Math.max(getUrlParam('page'), 100);
}

What we did in this small example is create our URLSearchParams 3 times. This is not very effective, let’s improve it.

One function to handle all the cases.

function getUrlParam(param) {
  if (typeof getUrlParam.usp === 'undefined' || getUrlParam.search !== window.location.search) {
    getUrlParam.search = window.location.search;
    getUrlParam.usp = new URLSearchParams(getUrlParam.search);
  }
  return getUrlParam.usp.get(param);
}

What we have now is something that checks whether the window.location.search has changed, or whether we are running it the first time, and initializes it. This makes sure that when the parameters change, the URLSearchParams is also re-instantiated.

Let’s also add a twist, and make sure we can get all parameters:

function getUrlParam(param) {
  if (typeof getUrlParam.usp === 'undefined' || getUrlParam.search !== window.location.search) {
    getUrlParam.search = window.location.search;
    getUrlParam.usp = new URLSearchParams(getUrlParam.search);
  }
  if (typeof param === 'undefined') {
    return Object.fromEntries(getUrlParam.usp.entries());
  }
  return getUrlParam.usp.get(param);
}

Now we can use it in two ways:

getUrlParam('action'); // will return value of parameter 'action'
getUrlParam(); // will return a key-value object with all parameters

Leave a Comment

Your email address will not be published.