RadDevon

How to Access Query Parameters in Javascript

Intro to Query Parameters

Query parameters are those funny strings in a URL after the question mark (?). Here’s an example of a URL with a query parameter:

https://www.google.com/search?q=what+is+a+url+parameter

In this example, Google has added a URL parameter when I searched that contains the contents of my search query. (They add a ton of other parameters too. Go try a search and check the location bar to see what I mean.)

This URL has a single query parameter: q. URLs can have multiple parameters, though. Each parameter has a value after its equals sign, and they are separated from other parameters by the ampersand (&). You don’t often need to get to them in your front-end Javascript, but, when you do, it’s not the easiest thing in the world to wrangle. Javascript doesn’t have good tools to help us deal with query parameters, so we’ll have to do most of it on our own.

What Are They Good For?

Query parameters let you save a tiny bit of state in the URL. If you try the example Google URL above, you’ll notice my search is still in the Google search box. I don’t have to tell you to go to Google and type the same search query; I just give you the URL with the query already stored in a query parameter. Google knows to show you the results of that search. You can similarly use query parameters to store some of the state of your application. Sometimes, you may even want to know about this state on the front-end. If so, this post can help.

Getting the Parameter String

We can use the window’s location object to get the parameter string. The parameter string is in the search property.

const queryParamsString = window.location.search.substr(1);

Parsing the Parameters

It would be be nice to have the parameters as an object. That way, if we wanted to get the value of a parameter called name, we could do it like this:

queryParams.name;

We can do this pretty simply by combining the split method with the array type’s reduce method.

Each query parameter is separated by an ampersand, so we’ll split the string on that.

queryParamsString.split('&');

The nice thing about split is that, if the delimiter you pass doesn’t appear in the string, you’ll get back an array with a single string containing the entire original string. This means you can run split on query strings with a single parameter or on those with multiple parameters and both will work. It also means you can run array methods on the output in either case since you know it will always be an array.

Reduce to an Object

We’ll use reduce to split each parameter string into its key and value, building an object from those keys and values.

const queryParams = queryParamsString .split('&') .reduce((accumulator, singleQueryParam) => { const [key, value] = singleQueryParam.split('='); accumulator[key] = value; return accumulator; }, {});

Let’s break this down. We have a constant queryParams that we’re assigning the value returned by the rest of the code here. We split queryParamsString on the ampersand which gives us an array of strings, each containing the string for a single query parameter. Here’s what that array would look like given the example URL at the top of the top of the post: ['q=what+is+a+url+parameter']

Then, we reduce that array starting with an empty object as the accumulator. (You’ll find the empty object passed in just before the closing parenthesis of the reduce call.)

To do that reduction, we first split the current parameter string on its equals sign giving us an array with the parameter name as the first value and the value of that parameter as the second. (Sometimes, query parameters don’t have an equals sign. We intentionally don’t account for those here, but your application may need to.) We unpack the resulting array and assign it to the variables key and value. That’s a cool new way you can assign individual array values to variables in ES6.

Finally, we add this new key/value pair to the accumulator object. We use square brackets so we can use a variable key name. We assign that key the value.

Making Spaces and Special Characters Work

The app is mostly complete, but it has one big problem. You’ll notice it when you try to use a query parameter with a space (or another special character). Since URLs can’t handle these characters, they get encoded so that they can be preserved in the URL. (For more detail, check out Alan Skorkin’s post on URLs. Read the section about special characters.)

For example, a space becomes %20 in the encoded parameter value. (Note: In the example URL from Google, and in many other apps that use search query parameters, the plus sign is used rather than the URL encoding for a space. If you want to handle this, you’d need to write custom code to replace plus signs with spaces. A regular expression would work nicely for this.)

In our app as it stands, an encoded space comes out as the encoding instead of as a space. We need to decode the values as we pull them out of the query string. To do this, we can use the Javascript global function decodeURIComponent. It’s really simple: it takes a URL-encoded string and returns a decoded string.

const queryParams = queryParamsString .split('&') .reduce((accumulator, singleQueryParam) => { const [key, value] = singleQueryParam.split('='); accumulator[key] = decodeURIComponent(value); return accumulator; }, {});

Instead of assigning the value directly in our reduction, we decode it first to make sure the intended value comes through. Now, we can get all the data from the URL regardless of which characters are encoded.

Try It Out on the Playground

We now have all the pieces in place for basic query parameter handling. Let’s try it out! I built a simple playground app so you can see how everything fits together and experiment with some different query parameters and values. If you’d like to try it out, check out the query parameters playground.